微信訂閱號天氣預報功能的實現(java版)
阿新 • • 發佈:2019-02-07
實現天氣預報的功能我用的是車聯網的api,所以首先我們在百度開發者中心api中找到車聯網api,然後在左側導航欄的介面說明找到天氣查詢的介面說明,如下圖:
然後我們看到返回的json格式資料:
整套開發體系我是用的劉峰老師的那一套,然後是在他的那一套框架上開發的,大家有什麼問題可以去看看他的,寫的很詳細的。接下來在搭建好的微信開發框架中,我們根據返回的json資料格式做相應的實現。首先寫javabean層
然後寫相應的功能實現類package com.yc.bean; import java.util.List; import java.util.Map; public class Weather { private String currentCity;//當前城市 private List<Map<String,String>> index;//返回json中的index陣列 private List<Map<String,String>> weather_data;//返回的json資料中的weather_data陣列 public String getCurrentCity() { return currentCity; } public void setCurrentCity(String currentCity) { this.currentCity = currentCity; } public List<Map<String, String>> getIndex() { return index; } public void setIndex(List<Map<String, String>> index) { this.index = index; } public List<Map<String, String>> getWeather_data() { return weather_data; } public void setWeather_data(List<Map<String, String>> weather_data) { this.weather_data = weather_data; } }
package com.yc.service; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Test; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import com.yc.bean.Weather; import com.yc.message.resp.Article; import com.yc.message.resp.NewsMessage; import com.yc.utils.Constants; public class WeatherService { /** * 傳送http請求 * * @param requestUrl 請求地址 * @return String */ private static String httpRequest(String requestUrl) { StringBuffer buffer = new StringBuffer(); try { URL url = new URL(requestUrl); HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection(); httpUrlConn.setDoInput(true); httpUrlConn.setRequestMethod("GET"); httpUrlConn.connect(); // 將返回的輸入流轉換成字串 InputStream inputStream = httpUrlConn.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String str = null; while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } bufferedReader.close(); inputStreamReader.close(); // 釋放資源 inputStream.close(); inputStream = null; httpUrlConn.disconnect(); } catch (Exception e) { e.printStackTrace(); } return buffer.toString(); } public static Weather weatherDetect(String place){ Weather weather=new Weather(); //天氣查詢地址 String queryUrl=Constants.SENDPATH4; try { //對url進行編碼 queryUrl = queryUrl.replace("LOCATION", java.net.URLEncoder.encode(place, "UTF-8")); //呼叫天氣查詢介面 String json = httpRequest(queryUrl); //System.out.println(json); //解析返回的json JSONObject jsonObj=JSONObject.fromObject(json); JSONArray results=jsonObj.getJSONArray("results"); //System.out.println(results.toString()); JSONObject resultsObject=(JSONObject) results.get(0); JSONArray index=resultsObject.getJSONArray("index"); JSONArray weather_data=resultsObject.getJSONArray("weather_data"); List<Map<String,String>> indexList=new ArrayList<Map<String,String>>(); for(int i=0;i<index.size();i++){ JSONObject info=index.getJSONObject(i); Map<String,String> map=new HashMap<String,String>(); map.put("title", info.getString("title")); map.put("zs", info.getString("zs")); map.put("tipt", info.getString("tipt")); map.put("des", info.getString("des")); indexList.add(map); } weather.setIndex(indexList); //System.out.println(weather.getIndex()); List<Map<String,String>> weather_dataList=new ArrayList<Map<String,String>>(); for(int i=0;i<weather_data.size();i++){ JSONObject info=weather_data.getJSONObject(i); Map<String,String> map=new HashMap<String,String>(); map.put("date", info.getString("date")); map.put("dayPictureUrl", info.getString("dayPictureUrl")); map.put("nightPictureUrl", info.getString("nightPictureUrl")); map.put("weather", info.getString("weather")); map.put("wind", info.getString("wind")); map.put("temperature", info.getString("temperature")); weather_dataList.add(map); } weather.setWeather_data(weather_dataList); //System.out.println(weather.getWeather_data()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return weather; } public static void main(String[] args) { weatherDetect("長沙").getIndex(); System.out.println(weatherDetect("長沙").getIndex()); } }
</pre><pre name="code" class="java">在這裡我封裝了一個類,專門放一個api呼叫連線的,之前在WeatherService呼叫的即SENDPATH4,後面的apikey大家可以換成自己在百度開發者的
<pre name="code" class="java">package com.yc.utils; /** * 一些常用的連結 * @author Administrator * */ public class Constants { //手機號碼歸屬地查詢 public static final String SENDPATH="http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo"; //笑話 public static final String SENDPATH2="http://api100.duapp.com/joke/?appkey=trialuser"; //智慧聊天 //public static final String SENDPATH3="http://www.wendacloud.com/openapi/api?key=bbab79b3f2feaf07e40553265f112aae&info="; public static final String SENDPATH3="http://xiao.douqq.com/api.php?msg="; //天氣查詢 public static final String SENDPATH4="http://api.map.baidu.com/telematics/v3/weather?location=LOCATION&output=json&ak=81218080E79C9685b35e757566d8cbe5"; //熱門影片 public static final String SENDPATH5="http://api.map.baidu.com/telematics/v3/movie?qt=hot_movie&location=LOCATION&output=json&ak=81218080E79C9685b35e757566d8cbe5"; //景點詳情 public static final String SENDPATH6="http://api.map.baidu.com/telematics/v3/travel_attractions?id=ID&output=json&ak=81218080E79C9685b35e757566d8cbe5"; }
以下是在呼叫類實現的呼叫:
//天氣查詢服務
else if(content.startsWith("天氣")){
String keyWord = content.replaceAll("^天氣", "").trim();
if ("".equals(keyWord)) {
textMessage.setContent(getWeatherUsage());
respMessage = MessageUtil.textMessageToXml(textMessage);
}else if(keyWord.startsWith("明後")){
keyWord = keyWord.replaceAll("^明後", "").trim();
Weather weather=new Weather();
weather=WeatherService.weatherDetect(keyWord);
List<Map<String,String>> weather_data=new ArrayList<Map<String,String>>();
weather_data=weather.getWeather_data();
// 建立圖文訊息
NewsMessage newsMessage = new NewsMessage();
newsMessage.setToUserName(fromUserName);
newsMessage.setFromUserName(toUserName);
newsMessage.setCreateTime(new Date().getTime());
newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
newsMessage.setFuncFlag(0);
List<Article> articleList = new ArrayList<Article>();
//多圖文訊息
Article article1 = new Article();
article1.setTitle(weather_data.get(1).get("date")+"\n"+weather_data.get(1).get("weather")+weather_data.get(1).get("wind")+weather_data.get(1).get("temperature"));
article1.setDescription("");
article1.setPicUrl(weather_data.get(1).get("dayPictureUrl"));
article1.setUrl("");
Article article2 = new Article();
article2.setTitle(weather_data.get(2).get("date")+"\n"+weather_data.get(2).get("weather")+weather_data.get(2).get("wind")+weather_data.get(2).get("temperature"));
article2.setDescription("");
article2.setPicUrl(weather_data.get(2).get("dayPictureUrl"));
article2.setUrl("");
Article article3 = new Article();
article3.setTitle("以上即為小編為您提供的"+keyWord+"未來兩天的天氣資訊");
article3.setDescription("");
article3.setPicUrl("");
article3.setUrl("");
articleList.add(article1);
articleList.add(article2);
articleList.add(article3);
newsMessage.setArticleCount(articleList.size());
newsMessage.setArticles(articleList);
respMessage = MessageUtil.newsMessageToXml(newsMessage);
}
else{
//獲取返回的weather
Weather weather=new Weather();
weather=WeatherService.weatherDetect(keyWord);
List<Map<String,String>> index=new ArrayList<Map<String,String>>();
index=weather.getIndex();
List<Map<String,String>> weather_data=new ArrayList<Map<String,String>>();
weather_data=weather.getWeather_data();
String des="";
//將index裡面資料的拼接
for(int i=0;i<index.size();i++){
des+=index.get(i).get("title")+":"+index.get(i).get("zs")+"。"+index.get(i).get("tipt")+":"+index.get(i).get("des")+"\n";
}
// 建立圖文訊息
NewsMessage newsMessage = new NewsMessage();
newsMessage.setToUserName(fromUserName);
newsMessage.setFromUserName(toUserName);
newsMessage.setCreateTime(new Date().getTime());
newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
newsMessage.setFuncFlag(0);
List<Article> articleList = new ArrayList<Article>();
//多圖文訊息
Article article1 = new Article();
article1.setTitle(keyWord+" "+weather_data.get(0).get("date"));
article1.setDescription(weather_data.get(0).get("weather")+"\n"+weather_data.get(0).get("wind")+"\n"+weather_data.get(0).get("temperature")+"\n\n"+des);
article1.setPicUrl(weather_data.get(0).get("dayPictureUrl"));
article1.setUrl("");
articleList.add(article1);
newsMessage.setArticleCount(articleList.size());
newsMessage.setArticles(articleList);
respMessage = MessageUtil.newsMessageToXml(newsMessage);
}
}
好啦,整個天氣預報的功能就已經實現了。下面讓我們來看看執行的效果:
可能本文寫的不是很清楚,如果大家有問題的話可以掃下面二維碼加我關注,訂閱號裡有聯絡方式的。大家可以一起交流,畢竟我也是菜鳥,自己做的訂閱號,有不足的地方也還請指教!謝謝
!