使用的是struts框架,調用結果返回出weatherResult【json格式】,再傳到前臺
public String getWeather() {
System.out.PRintln("hello weather");BufferedReader reader = null;StringBuffer sbf = new StringBuffer();String httpUrl = "http://apis.baidu.com/apix/idauth/idauth" + "?" + "name=刘坤&cardno=320921199108025071";try {URL url = new URL(httpUrl);HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setRequestMethod("GET");// 填入apikey到HTTP headerconnection.setRequestProperty("apikey","3286167d75112ab25de8936c7a270b35");connection.connect();InputStream is = connection.getInputStream();reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));String strRead = null;while ((strRead = reader.readLine()) != null) {sbf.append(strRead);sbf.append("/r/n");}reader.close();weatherResult = sbf.toString();} catch (Exception e) {e.printStackTrace();}System.out.println(weatherResult);return SUCCESS;}
json數據示例:
{ "HeWeather data service 3.0": [{ "status": "ok", //接口狀態,參考http://www.heweather.com/documents/api "basic": { //基本信息 "city": "故宮博物院", //景點名稱 "cnty": "中國", //國家 "id": "CN10101010018A", //景點ID,參見http://www.heweather.com/documents/cn-attractions-list "lat": "116.39", //城市維度 "lon": "39.91", //城市經度 "update": { //更新時間,景點天氣每天更新三次,分別為8、15、18點 "loc": "2015-07-02 08:10", //當地時間,如無特殊說明,以下時間均為當地時間 "utc": "2015-07-02 00:10" //UTC時間 } }, "daily_forecast": [ //7天預報 { "date": "2015-10-10", //預報日期,第一天 "astro": { //天文數值 "sr": "06:19", //日出時間 "ss": "17:43" //日落時間 }, "cond": { //天氣狀況,天氣狀況代碼和圖標,參考http://www.heweather.com/documents/condition-code "code_d": "101", //白天天氣狀況代碼 "code_n": "101", //夜間天氣狀況代碼 "txt_d": "多云", //白天天氣狀況描述 "txt_n": "多云" //夜間天氣狀況描述 }, "tmp": { //溫度 "max": "16", //最高溫度 "min": "10" //最低溫度 }, "wind": { //風力風向 "dir": "北風", //風向 "sc": "3-4" //風力 } }, {......}//第二到第七天重復以上內容,略 ] } ]}本本參考http://apistore.baidu.com/apiworks/servicedetail/880.html,勿噴
新聞熱點
疑難解答