和风天气调用

  private String key = "去控制台申请,控制台地址:https://console.qweather.com/#/apps";


    /*
     * 获取天气信息
     * 传入参数
     * */
    @RequestMapping(value = "hFWeather.html", method = RequestMethod.GET)
    public void hFWeather(HttpServletRequest request, HttpServletResponse rsp) {
        String result = "";
        String code = "-1";
        String msg = "传入参数不正确";
        //需要查询地区的LocationID或以英文逗号分隔的经度,纬度坐标(十进制,最多支持小数点后两位)
        //例如 location=101010100 或 location=116.41,39.92
        String location = request.getParameter("location");
        String lon = request.getParameter("LON");
        String lat = request.getParameter("LAT");
        HttpGet httpGet = null;
        HttpGet httpGetSs = null;
        HttpGet httpGetGeo = null;
        //判断是否传入了参数
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 响应模型
        CloseableHttpResponse response = null;
        CloseableHttpResponse responseSs = null;
        CloseableHttpResponse responseGeo = null;
        try {
            if (StringFacs.isEmpty(lon) || StringFacs.isEmpty(lat)) {
                location = "101080601";//默认为赤峰市
            } else {
                location = String.format("%.2f", new BigDecimal(lon)) + "," + String.format("%.2f", new BigDecimal(lat));
            }
            // 参数
            StringBuffer params = new StringBuffer();
            params.append("location=" + location);
            params.append("&");
            params.append("key=" + key);
            // 创建Get请求
            //7天
            httpGet = new HttpGet("https://devapi.qweather.com/v7/weather/7d" + "?" + params);
            //实时
            httpGetSs = new HttpGet("https://devapi.qweather.com/v7/weather/now" + "?" + params);
            //城市搜索
            httpGetGeo = new HttpGet("https://geoapi.qweather.com/v2/city/lookup" + "?" + params);
            // 配置信息
            RequestConfig requestConfig = RequestConfig.custom()
                    // 设置连接超时时间(单位毫秒)
                    .setConnectTimeout(5000)
                    // 设置请求超时时间(单位毫秒)
                    .setConnectionRequestTimeout(5000)
                    // socket读写超时时间(单位毫秒)
                    .setSocketTimeout(5000)
                    // 设置是否允许重定向(默认为true)
                    .setRedirectsEnabled(true).build();
            // 将上面的配置信息 运用到这个Get请求里
            httpGet.setConfig(requestConfig);
            httpGetSs.setConfig(requestConfig);
            httpGetGeo.setConfig(requestConfig);
            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpGet);
            responseSs = httpClient.execute(httpGetSs);
            responseGeo = httpClient.execute(httpGetGeo);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            HttpEntity responseSsEntity = responseSs.getEntity();
            HttpEntity responseGeoEntity = responseGeo.getEntity();
            /*System.out.println("响应状态为:" + response.getStatusLine());*/
            Map m = new HashMap();
            Map ma = new HashMap();
            ArrayList arrayList = new ArrayList();
            Map map = null;
            if (responseEntity != null) {
                result = EntityUtils.toString(responseEntity);
                JSONObject jsonObject = JSONObject.fromObject(result);
                JSONArray daily = JSONArray.fromObject(jsonObject.get("daily"));
                for (int i = 0; i < daily.size(); i++) {
                    map = new HashMap();
                    JSONObject dailyData = JSONObject.fromObject(daily.get(i));
                    String high = String.valueOf(dailyData.get("tempMax"));//high最高温度
                    String low = String.valueOf(dailyData.get("tempMin"));//low最高温度
                    String type = String.valueOf(dailyData.get("textDay"));//type天气
                    String fengxiang = String.valueOf(dailyData.get("windDirDay"));//fengxiang风向
                    String date = String.valueOf(dailyData.get("fxDate"));//date日期
                    String fengli = String.valueOf(dailyData.get("windScaleDay"));//风力

                    map.put("high", "aaa" + high);
                    map.put("low", "aaa" + low);
                    map.put("type", type);
                    map.put("fengxiang", fengxiang);
                    map.put("date", date);
                    map.put("fengli", fengli);
                    arrayList.add(map);
                }

                ma.put("forecast", JSONArray.fromObject(arrayList));
            }
            if (responseSsEntity != null) {
                String text = EntityUtils.toString(responseSsEntity);
                JSONObject nowJson = JSONObject.fromObject(text);
                JSONObject nowData = JSONObject.fromObject(nowJson.get("now"));
                ma.put("ganmao", String.valueOf(nowData.get("text")));
                ma.put("wendu", String.valueOf(nowData.get("temp")));
            }
            if (responseSsEntity != null) {
                String Geo = EntityUtils.toString(responseGeoEntity);
                JSONObject GeoJson = JSONObject.fromObject(Geo);
                JSONArray nowData = JSONArray.fromObject(GeoJson.get("location"));
                ma.put("city", String.valueOf(JSONObject.fromObject(nowData.get(0)).get("adm1")));
            }
            m.put("data", JSONObject.fromObject(ma));
            code = "0";
            msg = "天气获取成功";
            //组织返回结果
            result = "{\"code\":\"" + code + "\",\"msg\":\"" + msg + "\",\"data\":[" + JSONObject.fromObject(m) + "]}";
        } catch (Exception e) {
            result = "";
            code = "-1";
            msg = "天气获取失败";
            //组织返回结果
            result = "{\"code\":\"" + code + "\",\"msg\":\"" + msg + "\",\"data\":[" + result + "]}";
            System.out.println("app获取天气的接口报错--hFWeather.html报错");
        } finally {
            try {
                // 释放资源
                response.close();
                responseSs.close();
                responseGeo.close();
                httpClient.close();

            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        //调用打印方法返回给前台
        PrintWriterUtil.print(result, rsp);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值