请求某些网站的图片时
/**
- 根据一个网络连接(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();
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
} 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 = <span style="color: #000080;">**new**</span> URL(searchURL);
URLConnection myConn = (HttpURLConnection)myUrl.openConnection();
myConn.setRequestProperty(<span style="color: #ff0000;">"User-agent"</span>,<span style="color: #ff0000;">"Mozilla/4.0"</span>);
BufferedReader br = <span style="color: #000080;">**new**</span> BufferedReader(<span style="color: #000080;">**new**</span> InputStreamReader(myConn.getInputStream()));
那台Server上要这么做, 可能是要阻止一些网络机器人的访问(不过感觉不是很有用,用上面的方法就能破了)。
其实实现感觉也很简单, 加上一个Filter,判断如果request.getHeader(“User-agent”)为空的话,然后再response一个403 status就行。
💬 评论