天氣預報

到目前爲止,我們的公衆號已經可以回覆用戶發出的消息,但是如果僅僅如此,就沒必要設爲開發模式了。完全不懂編程的人也可以在微信公衆平臺上設置回覆用戶的消息。

現在我們來實現我們的公衆號查詢全國各個城市天氣這麼一個功能,像公衆號輸入天氣+地名(天氣南京)就可以查詢當地的天氣情況。
這裏寫圖片描述

具體實現

1.選擇API

我們使用阿里雲的全國天氣預報查詢接口。根據API說明,調用地址:http(s)://ali-weather.showapi.com/area-to-weather,請求方式:GET,返回類型:JSON

請求參數:

名稱 是否必須 描述
area 可選 地區名稱。名稱和id必須輸入一個。如果都輸入,以areaid爲準。
areaid 可選 地區id
need3HourForcast 可選 是否需要每小時數據的累積數組。由於本系統是半小時刷一次實時狀態,因此實時數組最大長度爲48。每天0點長度初始化爲0. 1爲需要 0爲不
needAlarm 可選 是否需要天氣預警。1爲需要,0爲不需要。
needHourData 可選 是否需要每小時數據的累積數組。由於本系統是半小時刷一次實時狀態,因此實時數組最大長度爲48。每天0點長度初始化爲0.
needIndex 可選 是否需要返回指數數據,比如穿衣指數、紫外線指數等。1爲返回,0爲不返回。
needMoreDay 可選 是否需要返回7天數據中的後4天。1爲返回,0爲不返回。

返回示例:

{
  "showapi_res_code": 0,
  "showapi_res_error": "",
  "showapi_res_body": {
    "f6": {//今天+5天后的天氣預報
      "day_weather": "小雨",//白天天氣
      "night_weather": "小雨",//晚上天氣
      "night_weather_code": "07",//晚上的天氣編碼
      "index": {//指數對象
        "cold": {//感冒
          "title": "少發",
          "desc": "無明顯降溫,感冒機率較低。"
        },
        "clothes": {//穿衣指數
          "title": "舒適",
          "desc": "建議穿長袖襯衫單褲等服裝。"
        },
        "uv": {//紫外線
          "title": "最弱",
          "desc": "輻射弱,塗擦SPF8-12防曬護膚品。"
        },
        "aqi": {//空氣質量指數,越小越好
          "title": "良",
          "desc": "氣象條件有利於空氣污染物擴散。"
        },
        "wash_car": {//洗車
          "title": "不宜",
          "desc": "有雨,雨水和泥水會弄髒愛車。"
        },
        "travel": {//旅遊
          "title": "較不宜",
          "desc": "有降水,推薦您在室內進行休閒運動。"
        }
      },
      "night_wind_power": "微風10m/h",//晚上風力編號
      "day_wind_power": "微風10m/h",//白天風力編號
      "day_weather_code": "07",//白天的天氣編碼
      "sun_begin_end": "06:28|20:17",//日出日落時間(中間用|分割)
      "day_weather_pic": "http://app1.showapi.com/weather/icon/day/07.png",//白天天氣圖標
      "weekday": 1,//星期幾
      "night_air_temperature": "15",//晚上天氣溫度(攝氏度)
      "day_air_temperature": "24",//白天天氣溫度(攝氏度)
      "day_wind_direction": "無持續風向",//白天風向編號
      "day": "20160704",//當前天
      "night_weather_pic": "http://app1.showapi.com/weather/icon/night/07.png",//晚上天氣圖標
      "night_wind_direction": "無持續風向"//晚上風向編號
    },
    "f7": {//今天+6天后的天氣預報
      "day_weather": "小雨",//白天天氣
      "night_weather": "中雨",//晚上天氣
      "night_weather_code": "08",//晚上的天氣編碼
      "index": {//指數對象
        "cold": {//感冒
          "title": "少發",
          "desc": "無明顯降溫,感冒機率較低。"
        },
        "clothes": {//穿衣指數
          "title": "較舒適",
          "desc": "建議穿薄外套或牛仔褲等服裝。"
        },
        "uv": {//紫外線
          "title": "最弱",
          "desc": "輻射弱,塗擦SPF8-12防曬護膚品。"
        },
        "wash_car": {//洗車
          "title": "較不宜",
          "desc": "有降水,推薦您在室內進行休閒運動。"
        },
        "travel": {//旅遊
          "title": "良",
          "desc": "氣象條件有利於空氣污染物擴散。"
        }
      },
      "night_wind_power": "微風10m/h",//晚上風力編號
      "day_wind_power": "微風10m/h",//白天風力編號
      "day_weather_code": "07",//白天的天氣編碼
      "sun_begin_end": "06:28|20:17",//日出日落時間(中間用|分割)
      "day_weather_pic": "http://app1.showapi.com/weather/icon/day/07.png",//白天天氣圖標
      "weekday": 2,//星期幾
      "night_air_temperature": "15",//晚上天氣溫度(攝氏度)
      "day_air_temperature": "23",//白天天氣溫度(攝氏度)
      "day_wind_direction": "無持續風向",//白天風向編號
      "day": "20160705",//當前天
      "night_weather_pic": "http://app1.showapi.com/weather/icon/night/08.png",//晚上天氣圖標
      "night_wind_direction": "無持續風向"//晚上風向編號
    },
    "time": "20160629113000",//預報發佈時間
    "ret_code": 0,
    "cityInfo": {//查詢的地區基本資料
      "c6": "yunnan",//城市所在省英文名
      "c5": "麗江",//城市所在市中文名
      "c4": "lijiang",//城市所在市英文名
      "c3": "麗江",//城市中文名
      "c9": "中國",//城市所在國家中文名
      "c8": "china",//城市所在國家英文名
      "c7": "雲南",//城市所在省中文名
      "c17": "+8",
      "c16": "AZ9888",//雷達站號
      "c1": "101291401",//區域id
      "c2": "lijiang",//城市英文名
      "c11": "0888",//城市區號
      "longitude": 100.222,//經度
      "c10": "2",//城市級別
      "latitude": 26.903,//緯度
      "c12": "674100",//郵編
      "c15": "2394"//海拔
    },
    "now": {//現在實時的天氣情況
      "aqiDetail": {//aqi明細數據
        "co": 0.38,//一氧化碳1小時平均
        "so2": 8,//二氧化硫1小時平均
        "area": "麗江",//地區
        "o3": 42,//臭氧1小時平均
        "no2": 9,//二氧化氮1小時平均
        "area_code": "lijiang",
        "quality": "優",//空氣質量指數類別,有“優、良、輕度污染、中度污染、重度污染、嚴重污染”6類
        "aqi": 19,//空氣質量指數,越小越好
        "pm10": 18,//顆粒物(粒徑小於等於10μm)1小時平均
        "pm2_5": 12,//顆粒物(粒徑小於等於2.5μm)1小時平均
        "o3_8h": 37,//臭氧8小時平均
        "primary_pollutant": ""//首要污染物
      },
      "weather_code": "03",
      "wind_direction": "西北風",//風向
      "temperature_time": "16:01",//獲得氣溫的時間
      "wind_power": "1級",//風力
      "aqi": 19,//空氣質量指數,越小越好
      "sd": "70%",//空氣溼度
      "weather_pic": "http://appimg.showapi.com/images/weather/icon/day/03.png",//天氣小圖標
      "weather": "陣雨",//天氣
      "temperature": "21"//氣溫
    },
    "f1": {//今天的天氣預報
      "day_weather": "小雨",//白天天氣
      "night_weather": "小雨",//晚上天氣
      "night_weather_code": "07",//晚上的天氣編碼
      "index": {//指數對象
        "yh": {//約會指數
          "title": "較不適宜",
          "desc": "建議儘量不要去室外約會。"
        },
        "ls": {//晾曬指數
          "title": "不宜",
          "desc": "降水可能會淋溼衣物,請選擇在室內晾曬。"
        },
        "clothes": {//穿衣指數
          "title": "較舒適",
          "desc": "建議穿薄外套或牛仔褲等服裝。"
        },
        "dy": {//釣魚指數
          "title": "不宜",
          "desc": "天氣不好,不適宜垂釣。"
        },
        "beauty": {//化妝指數
          "title": "保溼",
          "desc": "請選用中性保溼型霜類化妝品。"
        },
        "xq": {//心情指數
          "title": "較差",
          "desc": "雨水可能會使心緒無端地掛上輕愁。"
        },
        "travel": {//旅遊
          "title": "適宜",
          "desc": "較弱降水和微風將伴您共赴旅程。"
        },
        "hc": {//划船指數
          "title": "不適宜",
          "desc": "天氣不好,建議選擇別的娛樂方式。"
        },
        "zs": {//中暑指數
          "title": "無",
          "desc": "氣溫不高,中暑機率極低。"
        },
        "cold": {//感冒
          "title": "較易發",
          "desc": "降溫幅度較大,預防感冒。"
        },
        "gj": {//逛街指數
          "title": "較適宜",
          "desc": "有降水,逛街需要帶雨具。"
        },
        "uv": {//紫外線
          "title": "最弱",
          "desc": "輻射弱,塗擦SPF8-12防曬護膚品。"
        },
        "cl": {//晨練指數
          "title": "較不宜",
          "desc": "室外鍛鍊請攜帶雨具。"
        },
        "glass": {//太陽鏡
          "title": "不需要",
          "desc": "白天能見度差不需要佩戴太陽鏡"
        },
        "wash_car": {//洗車
          "title": "不宜",
          "desc": "有雨,雨水和泥水會弄髒愛車。"
        },
        "aqi": {//空氣質量指數,越小越好
          "title": "中",
          "desc": "無需特別防護"
        },
        "ac": {//空調控制
          "title": "較少開啓",
          "desc": "體感舒適,不需要開啓空調。"
        },
        "mf": {//美髮指數
          "title": "一般",
          "desc": "建議選用防曬滋潤型護髮品或帶遮陽帽。"
        },
        "ag": {//過敏指數
          "title": "極不易發",
          "desc": "無需擔心過敏,可放心外出,享受生活。"
        },
        "pj": {//啤酒指數
          "title": "較適宜",
          "desc": "適量的飲用啤酒,注意不要過量。"
        },
        "nl": {//夜生活指數
          "title": "較不適宜",
          "desc": "建議夜生活最好在室內進行。"
        },
        "pk": {//放風箏指數
          "title": "不宜",
          "desc": "天氣不好,不適宜放風箏。"
        }
      },
      "air_press": "766 hPa",//大氣壓
      "jiangshui": "75%",//降水概率
      "night_wind_power": "微風10m/h",//晚上風力編號
      "day_wind_power": "微風10m/h",//白天風力編號
      "day_weather_code": "07",//白天的天氣編碼
      "sun_begin_end": "06:28|20:17",//日出日落時間(中間用|分割)
      "ziwaixian": "最弱",
      "day_weather_pic": "http://app1.showapi.com/weather/icon/day/07.png",//白天天氣圖標
      "weekday": 3,//星期幾
      "night_air_temperature": "15",//晚上天氣溫度(攝氏度)
      "day_air_temperature": "22",//白天天氣溫度(攝氏度)
      "day_wind_direction": "無持續風向",//白天風向編號
      "day": "20160629",//當前天
      "night_weather_pic": "http://app1.showapi.com/weather/icon/night/07.png",//晚上天氣圖標
      "night_wind_direction": "無持續風向"//晚上風向編號
    },
    "f3": {//今天+2天后的天氣預報
      "day_weather": "小雨",//白天天氣
      "night_weather": "中雨",//晚上天氣
      "night_weather_code": "08",//晚上的天氣編碼
      "index": {//指數對象
        "cold": {//感冒
          "title": "較易發",
          "desc": "天較涼,增加衣服,注意防護。"
        },
        "clothes": {//穿衣指數
          "title": "較舒適",
          "desc": "建議穿薄外套或牛仔褲等服裝。"
        },
        "uv": {//紫外線
          "title": "最弱",
          "desc": "輻射弱,塗擦SPF8-12防曬護膚品。"
        },
        "aqi": {//空氣質量指數,越小越好
          "title": "良",
          "desc": "氣象條件有利於空氣污染物擴散。"
        },
        "wash_car": {//洗車
          "title": "不宜",
          "desc": "有雨,雨水和泥水會弄髒愛車。"
        },
        "travel": {//旅遊
          "title": "較不宜",
          "desc": "有降水,推薦您在室內進行休閒運動。"
        }
      },
      "night_wind_power": "微風10m/h",//晚上風力編號
      "day_wind_power": "微風10m/h",//白天風力編號
      "day_weather_code": "07",//白天的天氣編碼
      "sun_begin_end": "06:28|20:17",//日出日落時間(中間用|分割)
      "day_weather_pic": "http://app1.showapi.com/weather/icon/day/07.png",//白天天氣圖標
      "weekday": 5,//星期幾
      "night_air_temperature": "13",//晚上天氣溫度(攝氏度)
      "day_air_temperature": "21",//白天天氣溫度(攝氏度)
      "day_wind_direction": "無持續風向",//白天風向編號
      "day": "20160701",//當前天
      "night_weather_pic": "http://app1.showapi.com/weather/icon/night/08.png",//晚上天氣圖標
      "night_wind_direction": "無持續風向"//晚上風向編號
    },
    "f2": {//今天+1天后的天氣預報
      "day_weather": "小雨",//白天天氣
      "night_weather": "小雨",//晚上天氣
      "night_weather_code": "07",//晚上的天氣編碼
      "index": {//指數對象
        "cold": {//感冒
          "title": "少發",
          "desc": "無明顯降溫,感冒機率較低。"
        },
        "clothes": {//穿衣指數
          "title": "舒適",
          "desc": "建議穿長袖襯衫單褲等服裝。"
        },
        "uv": {//紫外線
          "title": "最弱",
          "desc": "輻射弱,塗擦SPF8-12防曬護膚品。"
        },
        "aqi": {//空氣質量指數,越小越好
          "title": "良",
          "desc": "氣象條件有利於空氣污染物擴散。"
        },
        "wash_car": {//洗車
          "title": "不宜",
          "desc": "有雨,雨水和泥水會弄髒愛車。"
        },
        "travel": {//旅遊
          "title": "較不宜",
          "desc": "有降水,推薦您在室內進行休閒運動。"
        }
      },
      "night_wind_power": "微風10m/h",//晚上風力編號
      "day_wind_power": "微風10m/h",//白天風力編號
      "day_weather_code": "07",//白天的天氣編碼
      "sun_begin_end": "06:28|20:17",//日出日落時間(中間用|分割)
      "day_weather_pic": "http://app1.showapi.com/weather/icon/day/07.png",//白天天氣圖標
      "weekday": 4,//星期幾
      "night_air_temperature": "16",//晚上天氣溫度(攝氏度)
      "day_air_temperature": "24",//白天天氣溫度(攝氏度)
      "day_wind_direction": "無持續風向",//白天風向編號
      "day": "20160630",//當前天
      "night_weather_pic": "http://app1.showapi.com/weather/icon/night/07.png",//晚上天氣圖標
      "night_wind_direction": "無持續風向"//晚上風向編號
    },
    "f5": {//今天+4天后的天氣預報
      "day_weather": "陰",//白天天氣
      "night_weather": "小雨",//晚上天氣
      "night_weather_code": "07",//晚上的天氣編碼
      "index": {//指數對象
        "cold": {//感冒
          "title": "少發",
          "desc": "無明顯降溫,感冒機率較低。"
        },
        "clothes": {//穿衣指數
          "title": "舒適",
          "desc": "建議穿長袖襯衫單褲等服裝。"
        },
        "uv": {//紫外線
          "title": "最弱",
          "desc": "輻射弱,塗擦SPF8-12防曬護膚品。"
        },
        "aqi": {//空氣質量指數,越小越好
          "title": "較差",
          "desc": "氣象條件較不利於空氣污染物擴散。。"
        },
        "wash_car": {//洗車
          "title": "不宜",
          "desc": "有雨,雨水和泥水會弄髒愛車。"
        },
        "travel": {//旅遊
          "title": "較適宜",
          "desc": "較適宜進行各種戶內外運動。"
        }
      },
      "night_wind_power": "微風10m/h",//晚上風力編號
      "day_wind_power": "微風10m/h",//白天風力編號
      "day_weather_code": "02",//白天的天氣編碼
      "sun_begin_end": "06:28|20:17",//日出日落時間(中間用|分割)
      "day_weather_pic": "http://app1.showapi.com/weather/icon/day/02.png",//白天天氣圖標
      "weekday": 7,//星期幾
      "night_air_temperature": "14",//晚上天氣溫度(攝氏度)
      "day_air_temperature": "25",//白天天氣溫度(攝氏度)
      "day_wind_direction": "無持續風向",//白天風向編號
      "day": "20160703",//當前天
      "night_weather_pic": "http://app1.showapi.com/weather/icon/night/07.png",//晚上天氣圖標
      "night_wind_direction": "無持續風向"//晚上風向編號
    },
    "f4": {//今天+3天后的天氣預報
      "day_weather": "小雨",//白天天氣
      "night_weather": "多雲",//晚上天氣
      "night_weather_code": "01",//晚上的天氣編碼
      "index": {//指數對象
        "cold": {//感冒
          "title": "較易發",
          "desc": "天較涼,增加衣服,注意防護。"
        },
        "clothes": {//穿衣指數
          "title": "較舒適",
          "desc": "建議穿薄外套或牛仔褲等服裝。"
        },
        "uv": {//紫外線
          "title": "最弱",
          "desc": "輻射弱,塗擦SPF8-12防曬護膚品。"
        },
        "aqi": {//空氣質量指數,越小越好
          "title": "良",
          "desc": "氣象條件有利於空氣污染物擴散。"
        },
        "wash_car": {//洗車
          "title": "不宜",
          "desc": "有雨,雨水和泥水會弄髒愛車。"
        },
        "travel": {//旅遊
          "title": "較不宜",
          "desc": "有降水,推薦您在室內進行休閒運動。"
        }
      },
      "night_wind_power": "微風10m/h",//晚上風力編號
      "day_wind_power": "微風10m/h",//白天風力編號
      "day_weather_code": "07",//白天的天氣編碼
      "sun_begin_end": "06:28|20:17",//日出日落時間(中間用|分割)
      "day_weather_pic": "http://app1.showapi.com/weather/icon/day/07.png",//白天天氣圖標
      "weekday": 6,//星期幾
      "night_air_temperature": "15",//晚上天氣溫度(攝氏度)
      "day_air_temperature": "22",//白天天氣溫度(攝氏度)
      "day_wind_direction": "無持續風向",//白天風向編號
      "day": "20160702",//當前天
      "night_weather_pic": "http://app1.showapi.com/weather/icon/night/01.png",//晚上天氣圖標
      "night_wind_direction": "無持續風向"//晚上風向編號
    }
  }
}

2.返回數據的封裝

返回的是一個JSON格式數據,下面要將這些數據進行封裝,封裝的代碼就不貼了,需要的可以聯繫我。

3.我們使用阿里提供的HTTP發送請求工具類

package org.sm.util.ali;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class HttpUtils {

    /**
     * get
     * 
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @return
     * @throws Exception
     */
    public static HttpResponse doGet(String host, String path, String method, Map<String, String> headers, Map<String, String> querys) throws Exception {
    HttpClient httpClient = wrapClient(host);

    HttpGet request = new HttpGet(buildUrl(host, path, querys));
    for (Map.Entry<String, String> e : headers.entrySet()) {
        request.addHeader(e.getKey(), e.getValue());
    }

    return httpClient.execute(request);
    }

    /**
     * post form
     * 
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param bodys
     * @return
     * @throws Exception
     */
    public static HttpResponse doPost(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, Map<String, String> bodys) throws Exception {
    HttpClient httpClient = wrapClient(host);

    HttpPost request = new HttpPost(buildUrl(host, path, querys));
    for (Map.Entry<String, String> e : headers.entrySet()) {
        request.addHeader(e.getKey(), e.getValue());
    }

    if (bodys != null) {
        List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();

        for (String key : bodys.keySet()) {
        nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
        }
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
        formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
        request.setEntity(formEntity);
    }

    return httpClient.execute(request);
    }

    /**
     * Post String
     * 
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPost(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, String body) throws Exception {
    HttpClient httpClient = wrapClient(host);

    HttpPost request = new HttpPost(buildUrl(host, path, querys));
    for (Map.Entry<String, String> e : headers.entrySet()) {
        request.addHeader(e.getKey(), e.getValue());
    }

    if (StringUtils.isNotBlank(body)) {
        request.setEntity(new StringEntity(body, "utf-8"));
    }

    return httpClient.execute(request);
    }

    /**
     * Post stream
     * 
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPost(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, byte[] body) throws Exception {
    HttpClient httpClient = wrapClient(host);

    HttpPost request = new HttpPost(buildUrl(host, path, querys));
    for (Map.Entry<String, String> e : headers.entrySet()) {
        request.addHeader(e.getKey(), e.getValue());
    }

    if (body != null) {
        request.setEntity(new ByteArrayEntity(body));
    }

    return httpClient.execute(request);
    }

    /**
     * Put String
     * 
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPut(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, String body) throws Exception {
    HttpClient httpClient = wrapClient(host);

    HttpPut request = new HttpPut(buildUrl(host, path, querys));
    for (Map.Entry<String, String> e : headers.entrySet()) {
        request.addHeader(e.getKey(), e.getValue());
    }

    if (StringUtils.isNotBlank(body)) {
        request.setEntity(new StringEntity(body, "utf-8"));
    }

    return httpClient.execute(request);
    }

    /**
     * Put stream
     * 
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPut(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, byte[] body) throws Exception {
    HttpClient httpClient = wrapClient(host);

    HttpPut request = new HttpPut(buildUrl(host, path, querys));
    for (Map.Entry<String, String> e : headers.entrySet()) {
        request.addHeader(e.getKey(), e.getValue());
    }

    if (body != null) {
        request.setEntity(new ByteArrayEntity(body));
    }

    return httpClient.execute(request);
    }

    /**
     * Delete
     * 
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @return
     * @throws Exception
     */
    public static HttpResponse doDelete(String host, String path, String method, Map<String, String> headers, Map<String, String> querys) throws Exception {
    HttpClient httpClient = wrapClient(host);

    HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
    for (Map.Entry<String, String> e : headers.entrySet()) {
        request.addHeader(e.getKey(), e.getValue());
    }

    return httpClient.execute(request);
    }

    private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
    StringBuilder sbUrl = new StringBuilder();
    sbUrl.append(host);
    if (!StringUtils.isBlank(path)) {
        sbUrl.append(path);
    }
    if (null != querys) {
        StringBuilder sbQuery = new StringBuilder();
        for (Map.Entry<String, String> query : querys.entrySet()) {
        if (0 < sbQuery.length()) {
            sbQuery.append("&");
        }
        if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
            sbQuery.append(query.getValue());
        }
        if (!StringUtils.isBlank(query.getKey())) {
            sbQuery.append(query.getKey());
            if (!StringUtils.isBlank(query.getValue())) {
            sbQuery.append("=");
            sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
            }
        }
        }
        if (0 < sbQuery.length()) {
        sbUrl.append("?").append(sbQuery);
        }
    }

    return sbUrl.toString();
    }

    private static HttpClient wrapClient(String host) {
    HttpClient httpClient = new DefaultHttpClient();
    if (host.startsWith("https://")) {
        sslClient(httpClient);
    }

    return httpClient;
    }

    private static void sslClient(HttpClient httpClient) {
    try {
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(X509Certificate[] xcs, String str) {

        }

        public void checkServerTrusted(X509Certificate[] xcs, String str) {

        }
        };
        ctx.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx);
        ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = httpClient.getConnectionManager();
        SchemeRegistry registry = ccm.getSchemeRegistry();
        registry.register(new Scheme("https", 443, ssf));
    } catch (KeyManagementException ex) {
        throw new RuntimeException(ex);
    } catch (NoSuchAlgorithmException ex) {
        throw new RuntimeException(ex);
    }
    }
}

4.新建一個WeatherService服務類

package org.sm.service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.sm.message.rsp.data.weather.F1;
import org.sm.message.rsp.data.weather.F2;
import org.sm.message.rsp.data.weather.F3;
import org.sm.message.rsp.data.weather.ShowApi;
import org.sm.util.ali.HttpUtils;

import com.google.gson.Gson;

public class WeatherService {

    public static String getWeather(String area) {

    String host = "https://ali-weather.showapi.com";
    String path = "/area-to-weather";
    String method = "GET";
    // 需要購買,購買完後會給你一個appcode
    String appcode = "xxxxxxxxxxxxxxxxxxxxxxxxxxx";
    Map<String, String> headers = new HashMap<String, String>();
    // 最後在header中的格式(中間是英文空格)爲Authorization:APPCODE
    // 83359fd73fe94948385f570e3c139105
    headers.put("Authorization", "APPCODE " + appcode);
    Map<String, String> querys = new HashMap<String, String>();
    querys.put("area", area);
    querys.put("need3HourForcast", "0");
    querys.put("needAlarm", "0");
    querys.put("needHourData", "0");
    querys.put("needIndex", "0");
    querys.put("needMoreDay", "0");

    String result = null;
    try {
        HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
        System.out.println(response.toString());
        // 獲取response的body
        String json = EntityUtils.toString(response.getEntity());
        // 使用GSON框架,將json數據轉換成Java對象
        ShowApi api = new Gson().fromJson(json, ShowApi.class);
        result = getResult(api);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return result;
    }

    private static String getResult(ShowApi api) {
    StringBuffer buffer = new StringBuffer();
    F1 f1 = api.getShowapi_res_body().getF1();
    F2 f2 = api.getShowapi_res_body().getF2();
    F3 f3 = api.getShowapi_res_body().getF3();
    buffer.append("今天\n白天").append(f1.getDay_air_temperature()).append("度").append("  ").append(f1.getDay_weather()).append("  ").append(f1.getDay_wind_direction()).append("  ")
        .append(f1.getDay_wind_power()).append(" ,夜間").append(f1.getNight_air_temperature()).append("度").append("  ").append(f1.getNight_weather()).append("  ")
        .append(f1.getNight_wind_direction()).append("  ").append(f1.getNight_wind_power()).append("\n\n明天(").append(getMonthDay(1)).append(")").append("\n白天")
        .append(f2.getDay_air_temperature()).append("度").append("  ").append(f2.getDay_weather()).append("  ").append(f2.getDay_wind_direction()).append("  ").append(f2.getDay_wind_power())
        .append(" ,夜間").append(f2.getNight_air_temperature()).append("度").append("  ").append(f2.getNight_weather()).append("  ").append(f2.getNight_wind_direction()).append("  ")
        .append(f2.getNight_wind_power()).append("\n\n後天(").append(getMonthDay(2)).append(")").append("\n白天").append(f3.getDay_air_temperature()).append("度").append("  ")
        .append(f3.getDay_weather()).append("  ").append(f3.getDay_wind_direction()).append("  ").append(f3.getDay_wind_power()).append(" ,夜間").append(f3.getNight_air_temperature())
        .append("度").append("  ").append(f3.getNight_weather()).append("  ").append(f3.getNight_wind_direction()).append("  ").append(f3.getNight_wind_power());

    return buffer.toString();
    }

    /**
     * 獲取前/後n天日期(M月d日)
     * 
     * @return
     */
    private static String getMonthDay(int diff) {
    DateFormat df = new SimpleDateFormat("M月d日");
    Calendar c = Calendar.getInstance();
    c.add(Calendar.DAY_OF_YEAR, diff);
    return df.format(c.getTime());
    }

}

5.引入jar包

這裏寫圖片描述

6.修改下ServiceServlet中doPost方法

/**
     * 處理微信服務器發來的消息
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    // 將請求、響應的編碼均設置爲UTF-8(防止中文亂碼)
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");

    Map<String, String> map = null;
    try {
        map = MessageUtil.parseXml(request);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // 發送方帳號(open_id)
    String fromUserName = map.get("FromUserName");
    // 公衆帳號
    String toUserName = map.get("ToUserName");
    // 消息類型
    String msgType = map.get("MsgType");
    // 請求消息內容
    String content = map.get("Content");
    if ("text".equals(msgType) && content.startsWith("天氣")) {
        String area = content.substring(2);
        // 默認回覆此文本消息
        TextMessage textMessage = new TextMessage();
        textMessage.setToUserName(fromUserName);
        textMessage.setFromUserName(toUserName);
        textMessage.setCreateTime(new Date().getTime());
        textMessage.setMsgType("text");

        textMessage.setContent(WeatherService.getWeather(area));

        String respMessage = MessageUtil.textMessageToXml(textMessage);
        System.out.println(respMessage);
        // 響應消息
        PrintWriter out = response.getWriter();
        out.print(respMessage);
        out.close();
    }
    }

6.項目結構
這裏寫圖片描述

查詢天氣預報功能已經實現了,是不是很簡單。只要調用第三方接口就可以,而且還有相應的示例代碼。其中appcode需要我們自己購買對應的api,買完後會返回給我們,阿里雲裏面提供api還有很多,套路都是一樣自己可以試着玩玩。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章