我正在尝试从网址下载图片。我面临的问题是如果URL没有www然后我得到错误,但如果我添加www它工作正常。我从网络服务获得这些URL有可能有些人有www而有些没有,我正在寻找解决方案来摆脱这个问题。
如果网址如此,则没问题: 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();
}
}
非常感谢。
答案 0 :(得分:1)
检查网址以查看其是否包含www。
如果它没有,那么你可以将它添加到字符串中。用http://
替换http://www.
将是一种简单的方法。
这是一个例子
String URL = "http://grindzmyreels.com/wp-content/uploads/2013/02/minion.jpg";
//if URL doesnt contain www. then add it after the http://
if(!URL.contains("www.")) URL.replace("http://", "http://www.");
答案 1 :(得分:0)
如果您从webservice获取URL,请使用检查URL是否包含www。如果没有,则添加它。