1

I want to download image from the path. This is my code:

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());

But it returns me null in bm. Any ideas how to make this code to work?

shtkuh
  • 349
  • 1
  • 10
  • 22

2 Answers2

2

Try 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());
CaseyB
  • 24,780
  • 14
  • 77
  • 112
1

The spaces are not the problem ... I tried it with your url and it's working

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();
}

The important line is connection.setRequestProperty("User-agent", "Mozilla/4.0");
I don't know why that solves it, but it has obviously worked before here.

Community
  • 1
  • 1
taymless
  • 779
  • 2
  • 9
  • 24
  • 1
    That's a hack and not a solution. The generic solution (escape any "problematic" character) is provided by CaseyB – Herr K Apr 28 '11 at 13:09
  • Unfortunately `URLEncoder.encode()` "encodes" the string to `http%3A%2F%2Fwww.hospimedica.com%2Fimages%2Fstories%2Farticles%2Farticle_images%2F_CC%2F20110328+-+DJB146.gif` which throws a MalformedURLException... Maybe I didn't post the best solution, at least I tested it before I did ... – taymless Apr 28 '11 at 13:22
  • Btw. the URL is not the problem .. like I said in the first line of my answer. The link I posted shows another question regarding that problem, without even mentioning the URL. – taymless Apr 28 '11 at 13:26