天氣API接口的使用


最近項目中使用到了天氣預報的功能,需要從網上獲取天氣數據,然后顯示在公司系統的頁面上。

在這里和大家分享下我的做法,希望能對大家有所幫助,如果有錯誤,歡迎大家指正

先給大家看看效果:

 

下面開始進行講解。

1.找API接口

首先先去網上找一個免費的天氣API,這里推薦大家去百度API Store找,有免費使用的。

我是用的是    ,接口地址是:http://apis.baidu.com/heweather/weather/free

 

2.后台代碼

 

 1 package com.byteslounge.websockets;
 2 
 3 import bean.Response;
 4 
 5 import javax.net.ssl.HttpsURLConnection;
 6 import java.io.BufferedReader;
 7 import java.io.InputStream;
 8 import java.io.InputStreamReader;
 9 import java.net.HttpURLConnection;
10 import java.net.URL;
11 import java.util.HashMap;
12 import java.util.Map;
13 
14 
15 public class Weather {
16 
17     public static String requests(String httpUrl, String httpArg) {
18         BufferedReader reader = null;
19         String result = null;
20         StringBuffer sbf = new StringBuffer();
21         httpUrl = httpUrl + "?" + httpArg;
22 
23         try {
24             URL url = new URL(httpUrl);
25             HttpURLConnection connection = (HttpURLConnection) url
26                     .openConnection();
27             connection.setRequestMethod("GET");
28             // 填入apikey到HTTP header
29             connection.setRequestProperty("apikey",  "0bc030269671ad02d5730afb5c355b34");
30             connection.connect();
31             InputStream is = connection.getInputStream();
32             reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
33             String strRead = null;
34             while ((strRead = reader.readLine()) != null) {
35                 sbf.append(strRead);
36                 sbf.append("\r\n");
37             }
38             reader.close();
39             result = sbf.toString();
40         } catch (Exception e) {
41             e.printStackTrace();
42         }
43         return result;
44 }
45 }

 

 

 

3.前端JSP調用requests()方法

 

1 <%
2         //通過接口獲取天氣當天天氣數據
3         String jsons = new Weather().requests("http://apis.baidu.com/heweather/weather/free", "city=yinzhou");
4         String json = new Weather().requests("http://apis.baidu.com/heweather/weather/free", "city=ningbo");
5     %>

 

jsons里面的信息:

 

最后大家就可以使用json對數據進行獲取,再使用jquery將數據放置在頁面上了。這里給大家推薦個json轉化器,http://c.runoob.com/front-end/53,可以方便大家進行數據的提取。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM