springboot 整合線上天氣預報

一個小白開發發表於2020-12-03

前陣子專案中遇到了需要使用介面查詢天氣介面,之前以為很難,後面發現賊簡單,話不多說直接上程式碼

//    文字轉譯 設定時間超時
    public static final String DEF_CHATSET = "UTF-8";
    public static final int DEF_CONN_TIMEOUT = 30000; 
    public static final int DEF_READ_TIMEOUT = 30000;
//    代理商
    public static String userAgent =  "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";

Appkey 配置 Appkey 一定是要最真實的

    @Value("${forecast.appkey}")
    private String APPKEY;

下面是邏輯程式碼

    public AjaxJson findForecast(String cityname) {
//        先定義一個結果
        String result =null;
        String url ="http://apis.juhe.cn/simpleWeather/query";//請求介面地址
        Map params = new HashMap();//請求引數
        params.put("city",cityname);//要查詢的城市,如:溫州、上海、北京
        params.put("key",APPKEY);//應用APPKEY(應用詳細頁查詢)
        params.put("dtype","");//返回資料的格式,xml或json,預設json

        try {
            result =net(url, params, "GET");
              } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxJson.success().put("成功",result);
    }
  private String net(String strUrl, Map params, String method) throws Exception{
//        Object cityname = params.get("city");
//        System.out.println(cityname);
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String rs = null;
        try {
            StringBuffer sb = new StringBuffer();
            if(method==null || method.equals("GET")){
                strUrl = strUrl+"?"+urlencode(params);
//                System.out.println(strUrl);
            }
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            if(method==null || method.equals("GET")){
                conn.setRequestMethod("GET");
            }else{
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
            }
            conn.setRequestProperty("User-agent", userAgent);
            conn.setUseCaches(false);
            conn.setConnectTimeout(DEF_CONN_TIMEOUT);
            conn.setReadTimeout(DEF_READ_TIMEOUT);
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            if (params!= null && method.equals("POST")) {
                try {
                    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                    out.writeBytes(urlencode(params));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sb.append(strRead);
            }
            rs = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return rs;
    }

  public static String urlencode(Map<String,String> data) {
            StringBuilder sb = new StringBuilder();
            for (Map.Entry i : data.entrySet()) {
                try {
                    sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            return sb.toString();
        }

    }

以下是執行結果

{
  "msg": "操作成功",
  "code": 200,
  "成功": "{\"reason\":\"查詢成功!\",\"result\":{\"city\":\"成都\",\"realtime\":{\"temperature\":\"6\",\"humidity\":\"93\",\"info\":\"陰\",\"wid\":\"02\",\"direct\":\"北風\",\"power\":\"2級\",\"aqi\":\"45\"},\"future\":[{\"date\":\"2020-12-03\",\"temperature\":\"4\\/6℃\",\"weather\":\"小雨轉陰\",\"wid\":{\"day\":\"07\",\"night\":\"02\"},\"direct\":\"持續無風向\"},{\"date\":\"2020-12-04\",\"temperature\":\"4\\/6℃\",\"weather\":\"陰\",\"wid\":{\"day\":\"02\",\"night\":\"02\"},\"direct\":\"持續無風向\"},{\"date\":\"2020-12-05\",\"temperature\":\"4\\/7℃\",\"weather\":\"陰\",\"wid\":{\"day\":\"02\",\"night\":\"02\"},\"direct\":\"持續無風向\"},{\"date\":\"2020-12-06\",\"temperature\":\"5\\/8℃\",\"weather\":\"小雨\",\"wid\":{\"day\":\"07\",\"night\":\"07\"},\"direct\":\"持續無風向\"},{\"date\":\"2020-12-07\",\"temperature\":\"5\\/9℃\",\"weather\":\"小雨\",\"wid\":{\"day\":\"07\",\"night\":\"07\"},\"direct\":\"持續無風向\"}]},\"error_code\":0}",
  "success": true
}

相關文章