关于HttpClient请求获取数据
2018-02-08 11:19
435 查看
httpClient请求获取网站数据
今天一网友问我,他写的httpClient请求为什么获取不到数据?他写的代码如下:StringBuffer buffer = new StringBuffer();
String url1 = "http://api.jisuapi.com/weather/query?appkey=8b650df3d443004f&city=贵阳";
try {
URL url = new URL(url1);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream is = conn.getInputStream();
Reader reader = new InputStreamReader(is,"utf-8");
char[] c = new char[1024];
int count = -1;
while ((count = reader.read(c)) > 0) {
buffer.append(c, 0, count);
}
reader.close();
JSONObject obj = JSONObject.parseObject(buffer.toString());
Weather weather = JSONObject.toJavaObject(obj, Weather.class);
model.addAttribute("msg",weather);
System.out.println(weather);
System.out.println(buffer.toString());
} catch (IOException e) {
e.printStackTrace();
}直接通过main方法运行是可以获取到的,但是通过系统页面点击却获取不到。甚是奇怪,至今我还没搞明白为什么上面的方法不行!希望有知道的大神可以告诉小弟下,感激不尽!!!
后来我给他换了一种方式,如下是我写的代码:String url = "http://api.jisuapi.com/weather/query?appkey=8b650df3d443004f&city=贵阳";
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet get = new HttpGet(url);
try {
CloseableHttpResponse response = httpClient.execute(get);
int statusCode =response.getStatusLine().getStatusCode();
System.out.println(statusCode);
if(statusCode == 200) {
HttpEntity entity =response.getEntity();
String content = EntityUtils.toString(entity,"utf-8");
System.out.println(content);
JSONObject obj = JSONObject.parseObject(content);
Weather weather = JSONObject.toJavaObject(obj, Weather.class);
model.addAttribute("msg",weather);
}
//关闭httpclient
response.close();
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}我用的比较多的就是这种,至于为什么上一个会获取不到,还希望知道的大神给予指教。
相关文章推荐
- android通过httpClient请求获取JSON数据并且解析
- android通过httpClient请求获取JSON数据并且解析
- HttpClient get和HttpClient Post请求的方式获取服务器的返回数据
- JAVA 爬虫之httpclient post请求提交表单获取Ajax数据
- android通过httpClient请求获取JSON数据并且解析
- android通过httpClient请求获取JSON数据并且解析
- android通过httpClient请求获取JSON数据并且解析
- android通过httpClient请求获取JSON数据并且解析
- android通过httpClient请求获取JSON数据并且解析
- android通过httpClient请求获取JSON数据并且解析
- HttpClient get和HttpClient Post请求的方式获取服务器的返回数据
- Android系列之网络(一)----使用HttpClient发送HTTP请求(通过get方法获取数据)
- Java用org.apache.http.client的HttpClient发送Post请求 可获取返回Header
- HttpClient获取并解析JSON数据
- Java用org.apache.http.client的HttpClient发送Post请求 可获取返回Header
- android获取URLConnection和HttpClient网络请求响应码
- HttpClient获取网络数据
- OkHttpClient post请求今日头条数据 RecycleView显示
- 关于iOS 数据请求ASIHttpRequest方法的总结
- HttpClient获取并解析JSON数据