How to handle empty space in url when downloading

2019-07-21 07:29发布

I'm working on a project where the url sometimes can have empty spaces in it (not always) example: www.google.com/ example/test.jpg and sometimes www.google.com/example/test.jpg.

My code:

     try {
            URL url = new URL(stringURL);
            URLConnection conexion = url.openConnection();
            conexion.connect();

            // downlod the file
            InputStream input = new BufferedInputStream(url.openStream(), 8192);
            OutputStream output = new FileOutputStream(fullPath.toString());

            byte data[] = new byte[1024];

            while ((count = input.read(data)) != -1) {
                output.write(data, 0, count);
            }
            output.flush();
            output.close();
            input.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

It's this line that fails: InputStream input = new BufferedInputStream(url.openStream(), 8192);

with a: java.io.FileNotFoundException.

I've tryed to encode the specific line but here is the kicker: the server needs the empty space " " in order to find the file, so I need to have the empty space somehow. I can find the file (jpg) if i use firefox browser. Any help much appreciated.

Edit update: Well now I've tryed to encode every single bit after the host part of the url to utf-8 and I've tryed using both + and %20 for blank space. Now I can manage to DL the file but it will be faulty so it can't be read.

Edit update2: I had made a mistake with %20, that works.

1条回答
兄弟一词,经得起流年.
2楼-- · 2019-07-21 07:47

Okay I solved the headache.

First I use:

completeUrl.add(URLEncoder.encode(finalSeperated[i], "UTF-8"));

For every part of the url between "/"

Then I use:

    ArrayList<String> completeUrlFix = new ArrayList<String>();
    StringBuilder newUrl = new StringBuilder();
    for(String string : completeUrl) {
        if(string.contains("+")) {
            String newString = string.replace("+", "%20");
            completeUrlFix.add(newString);
        } else {
            completeUrlFix.add(string);
        }
    }

    for(String string : completeUrlFix) {
        newUrl.append(string);
    }

To build a proper urlString.

The reason this works is because http needs %20. See Trouble Percent-Encoding Spaces in Java comment by Powerlord

查看更多
登录 后发表回答