【发布时间】:2013-06-14 09:48:45
【问题描述】:
我正在尝试从 URL 下载图像。我面临的问题是,如果 URL 没有 www,那么我会收到错误,但如果我添加 www,它就可以正常工作。我从 Web 服务获取这些 URL,有的可能有 www,有的没有,我正在寻找解决这个问题的解决方案。
如果 URL 是这样的,那么没问题: http://www.grindzmyreels.com/wp-content/uploads/2013/02/minion.jpg
但在这种情况下我得到错误: http://grindzmyreels.com/wp-content/uploads/2013/02/minion.jpg
代码如下:
public void DownloadImage()
{
HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse;
Bitmap bmp = null;
try{
httpResponse = client.execute(new HttpGet("http://www.grindzmyreels.com/wp-content/uploads/2013/02/minion.jpg"));
//int responseCode = httpResponse.getStatusLine().getStatusCode();
HttpEntity entity = httpResponse.getEntity();
if (entity != null)
{
InputStream in = entity.getContent();
bmp = BitmapFactory.decodeStream(in);
in.close();
String Path = bmp.toString();
Context context = getApplicationContext();
File mydir = context.getDir("MyFolder", Context.MODE_PRIVATE); //Creating an internal dir;
File fileWithinMyDir = new File(mydir, Path ); //Getting a file within the dir.
FileOutputStream out = new FileOutputStream(fileWithinMyDir);
out.close();
extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
File file = new File(extStorageDirectory, Name+".PNG");
outStream = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 100, outStream);
filePath = file.toString();
outStream.flush();
outStream.close();
}
}
catch (ClientProtocolException e)
{
client.getConnectionManager().shutdown();
e.printStackTrace();
}
catch (IOException e)
{
client.getConnectionManager().shutdown();
e.printStackTrace();
}
}
非常感谢。
【问题讨论】: