使用Android中的路径中的空格从URL下载图像

时间:2011-04-28 12:36:55

标签: android bitmap

我想从路径下载图片。 这是我的代码:

String urlString = "http://www.hospimedica.com/images/stories/articles/article_images/_CC/20110328 - DJB146.gif";
url = new URL(urlString.replaceAll(" ", "%20"));
bm = BitmapFactory.decodeStream(url.openConnection().getInputStream());

但它在bm中返回null。任何想法如何使这个代码工作?

2 个答案:

答案 0 :(得分:2)

尝试UrlEncoder

String urlString = URLEncoder.encode("http://www.hospimedica.com/images/stories/articles/article_images/_CC/20110328 - DJB146.gif");
url = new URL(urlString);
bm = BitmapFactory.decodeStream(url.openConnection().getInputStream());

答案 1 :(得分:1)

这些空间不是问题......我用你的网址尝试了它并且它正在工作

try {
    String urlString = "http://www.hospimedica.com/images/stories/articles/article_images/_CC/20110328 - DJB146.gif";
    URL url = new URL(urlString.replaceAll(" ", "%20"));

    URLConnection connection = url.openConnection();
    connection.setRequestProperty("User-agent", "Mozilla/4.0");
    connection.connect();

    InputStream input = connection.getInputStream();

    Log.d("#####", "result: " + BitmapFactory.decodeStream(input));
} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

重要的一行是connection.setRequestProperty("User-agent", "Mozilla/4.0");
我不知道为什么会解决它,但它显然在here之前有效。