使用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/
调了一下午,发现需要给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/
相关文章推荐
- 使用OAuth2.0访问豆瓣API
- Apache HttpComponents 的使用入门(java使用HttpClient访问Api, 使用json.org库处理json数据)
- 使用Groovy访问豆瓣API
- 使用 httpclient 访问https接口问题(无证书访问https接口)
- vue使用axios调用豆瓣API跨域问题
- 使用httpClient访问指定网址遇到的问题
- 使用WebService访问Google api
- 关于struts Validator在多模块下多国语言资源访问的问题解决之道(一)struts Validator下使用多模块的多国语言资源
- 使用Visual Basic访问数据库几个注意的问题
- 使用Visual Basic访问数据库几个注意的问题
- 使用WebService访问Google api
- 使用Tomcat访问JSP页面时遇到的问题
- VB使用API实现串口通讯的异常问题
- 在sps中使用第三方smtp软件解决邮件服务器不允许匿名访问的问题
- 解决开启瑞星防火墙后网上邻居无法访问、共享打印机无法使用问题
- 使用WebService访问Google api
- 拒绝访问。 (异常来自 HRESULT:0x80070005 (E_ACCESSDENIED)) 使用Enterprise Library 3.0的磁盘缓存Isolated Storage 的问题
- 在WEB程序中使用.NET Remoting的IpcChannel时注意事项(关于“拒绝访问”问题的解决)
- 如何解决烦人的VS.NET2003编译时“无法将程序集复制到文件,另一个程序正在使用,进程无法访问”的问题?
- 如何解决ADO.NET访问Access数据库出现"操作必须使用一个可更新的查询"的问题