其他 · 2014年7月24日 0

HttpURLConnection 访问图片时发生403问题,使用DefaultHttpClient就OK

请求某些网站的图片时

/**
* 根据一个网络连接(String)获取bitmap图像
*
* @param imageUri
* @return
* @throws MalformedURLException
*/
public Bitmap getbitmap(String imageUri) {
// 显示网络上的图片
Bitmap bitmap = null;
try {
URL myFileUrl = new URL(imageUri);
HttpURLConnection conn = (HttpURLConnection) myFileUrl
.openConnection();
// conn.setDoInput(true);
conn.setRequestProperty(“User-agent”, “Mozilla/4.0”);
conn.connect();
Log.i(“–“, “conn.getResponseCode.” + conn.getResponseCode());
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();

Log.i(“–“, “image download finished.” + imageUri);
} catch (IOException e) {
e.printStackTrace();
return null;
}
return bitmap;
}

如果不添加conn.setRequestProperty(“User-agent”, “Mozilla/4.0”);这句会造成返回的状态code是403,

使用

public Bitmap loadImageFromUrl(String url) {
Bitmap d = null;
// URL m;
InputStream i = null;
try {
HttpGet get = new HttpGet(url);
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse re = client.execute(get);
i = re.getEntity().getContent();
} catch (MalformedURLException e1) {
e1.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
d = BitmapFactory.decodeStream(i);
return d;
}

就不会有这种情况,最后得到如下结论

当我用HttpURLConnection去连接读取一个网站时,老是会发生这个403错误。这个引起了IOException,但是我用firefox访问这个网站时就没问题。 google后知道了答案。原来如果用java代码HttpURLConnection去连的话 http header 中的User-Agent就为空,解决方法就是在连接之前先设置这个属性。

URL myUrl = new URL(searchURL);
URLConnection myConn = (HttpURLConnection)myUrl.openConnection();
myConn.setRequestProperty("User-agent","Mozilla/4.0");
BufferedReader br = new BufferedReader(new InputStreamReader(myConn.getInputStream()));

那台Server上要这么做, 可能是要阻止一些网络机器人的访问(不过感觉不是很有用,用上面的方法就能破了)。

其实实现感觉也很简单, 加上一个Filter,判断如果request.getHeader(“User-agent”)为空的话,然后再response一个403 status就行。

Share this: