关于HttpClient请求获取数据

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();
}
我用的比较多的就是这种,至于为什么上一个会获取不到,还希望知道的大神给予指教。  


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值