天气预报

来源:互联网 发布:java 获取对象的大小 编辑:程序博客网 时间:2024/06/18 11:46

到目前为止,我们的公众号已经可以回复用户发出的消息,但是如果仅仅如此,就没必要设为开发模式了。完全不懂编程的人也可以在微信公众平台上设置回复用户的消息。

现在我们来实现我们的公众号查询全国各个城市天气这么一个功能,像公众号输入天气+地名(天气南京)就可以查询当地的天气情况。
这里写图片描述

具体实现

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还有很多,套路都是一样自己可以试着玩玩。