Bad URL encoding for images

故事扮演 提交于 2019-12-13 00:38:35

问题


In my app, there is an ImageView that display an image from a URL.

I download the image using this method:

        Bitmap bitmap=null;
        URL imageUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
        conn.setConnectTimeout(30000);
        conn.setReadTimeout(30000);
        conn.setInstanceFollowRedirects(true);
        InputStream is=conn.getInputStream();
        OutputStream os = new FileOutputStream(f);
        Utils.CopyStream(is, os);
        os.close();
        bitmap = decodeFile(f);
        return bitmap;

This works only with URLs that has numbers or english letters and doesn't work with any other chars (like spaces):

Good URL: http://site.com/images/image.png

Bad URL: http://site.com/images/image 1.png

I tried to chage the URL encoding (URLEncoder.encode), but it changes the whole URL (incliding slashes, ect...).

Do I need to replace some chars after the encoding? or maybe there is a better way?

Thanks :)


回答1:


"Url encoding in Android"

You don't encode the entire URL, only parts of it that come from "unreliable sources". -yanchenko

String query = URLEncoder.encode("apples oranges", "utf-8");
String url = "https://stackoverflow.com/search?q=" + query;

This is fine if you are just dealing with a specific part of a URL and you know how to construct or reconstruct the URL. For a more general approach which can handle any url string, see my answer below. – Craig B

String urlStr = "http://abc.dev.domain.com/0007AC/ads/800x480 15sec h.264.mp4";
URL url = new URL(urlStr);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
url = uri.toURL();


来源:https://stackoverflow.com/questions/13324075/bad-url-encoding-for-images

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!