引入依赖:Http相关jar包,之前试了几个apache下的,在流处理时均有乱码,下面这个依赖是测试过没问题的,也比较方便
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.12</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> <version>4.4.6</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>${fastjson.version}</version> </dependency>搭配一个json使用,更加便捷。 通过和风提供的开发者api,访问地址为:https://devapi.heweather.net/v7/weather/now, 参数有2个 ,一个为location(城市代码比较推荐,比如101221001),二微key,即在和风上注册一个账户,自定义一个应用既可获取一个key。通过key来进行访问。 不过和风有次数限制,可以通过SOJSON上的天气接口来白嫖也行。 访问代码如下:
public String doGet(String url,Map<String,String> paramsMap){ String response = ""; String p = ""; if(paramsMap.size()>0){ p ="?location="+paramsMap.get("location").toString() + "&" + "key="+paramsMap.get("key").toString(); } if(!p.equals("")){ url = url + p; } CloseableHttpClient client = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(url); CloseableHttpResponse closeableHttpResponse = null; try{ closeableHttpResponse = client.execute(httpGet); HttpEntity entity = closeableHttpResponse.getEntity(); response = EntityUtils.toString(entity, "UTF-8"); }catch (Exception e ){ logger.error("网络通讯失败,url为:"+url+",异常为:"+e); }finally { try { closeableHttpResponse.close(); } catch (IOException e) { } } return response ; }自己将response进行json化处理成自己需要的类既可。