百度API对应的地址这个好难找:天气查询服务 | 百度地图API SDK
在应用控制台申请KEY:https://lbsyun.baidu.com/apiconsole/key
请求参数如图:
public static String getWeather(String code) { //4c777b6d102a562197ed74dce81ec377 String url = "https://api.map.baidu.com/weather/v1/?district_id="+code+"&data_type=all&ak=换成你的KEY"; Map params = new HashMap(); Map propertys = new HashMap(); String weather; try { weather = HttpUtils.sendGet(url, params, propertys); System.out.println(weather); JSONObject jo = JSON.parseObject(weather); StringBuffer sb = new StringBuffer(); if(jo.containsKey("status")&&jo.getIntValue("status")==0) { //解析出地址 JSONObject result = jo.getJSONObject("result"); JSONObject location = result.getJSONObject("location"); String city = location.getString("city"); String name = location.getString("name"); JSONObject now = result.getJSONObject("now"); String text = now.getString("text"); String temp = now.getString("temp"); String wind_class = now.getString("wind_class"); String wind_dir = now.getString("wind_dir"); JSONArray jarr = result.getJSONArray("forecasts"); sb.append("您好,"+city+""+name+"现在:"+text+"气温"+temp+"℃ 风力:"+wind_class+"风向"+wind_dir+"\n未来几日天气仅供参考\n"); for(int i=0;i<jarr.size();i++) { JSONObject arr = jarr.getJSONObject(i); String date = arr.getString("date"); String week = arr.getString("week"); String text_day = arr.getString("text_day"); String text_night = arr.getString("text_night"); String high = arr.getString("high"); String low = arr.getString("low"); sb.append(date+"("+week+") 白天"+text_day+" 晚上"+text_night+" 气温"+high+"~"+low+"℃\n"); } }else { sb.append("抱歉根据你的提问,我找不到对应的地区"); } return sb.toString(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
其中 district_id 是区县的行政区划编码,具体代码可参考这个文档下载后可以自己导入数据库:https://www.mbzj.net/article/view/507