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