您的位置:首页 > 理论基础 > 计算机网络

使用HTTPclient访问豆瓣API问题

2014-12-23 16:43 330 查看
在Android下,使用HTTPclient模拟get请求时,服务器返回500错误。但是,如果不是Android环境则没有问题,很诡异。

调了一下午,发现需要给httpget设置User-Agent。豆瓣你为何如此坑爹。

代码很简单:

public static String getBookJson(String isbn) {
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = null;
HttpResponse response = null;
String resultJson = null;
try {
httpGet = new HttpGet(baseUrl + isbn);
httpGet.setHeader("Host", "api.douban.com");
httpGet.setHeader(
"User-Agent",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36");
response = client.execute(httpGet);
int code = response.getStatusLine().getStatusCode();
if (code == 200) {

resultJson = EntityUtils
.toString(response.getEntity(), "utf-8");
Log.e("MainActivity", resultJson);
return resultJson;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";

}


就是这么简单的代码,你必须设置User-Agent,或者不使用HTTPclient,使用UrlConnecttion也可以。

参考:http://www.douban.com/group/topic/35873259/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android HTTPclient 豆瓣