Downloading image from URL with spaces in the path in Android
I want to download image from the path. This is my code:
String urlString = "http:开发者_JAVA技巧//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?
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());
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.
精彩评论