免費天氣預報接口

以下文章屬於原創,轉載請標明出處 http://www.pm-road.com/index.php/2014/08/27/81/

使用java實現本地天氣預報信息顯示

首先該接口是調用 中國天氣網的接口數據,也就是中國氣象局的數據。我這裏採用的訪問地址是:

http://www.weather.com.cn/data/cityinfo/      城市代碼爲101010100  (北京)

然後:寫後臺代碼:

1:先寫一個天氣預報的接口:IWeatherAPI 

裏面包括方法:

public interface IWeatherAPI {
/**
* 從host獲得相應的city 天氣字符串
* @return
*/
public String getWeatherStr() throws Exception;
/**
* 從host獲得相應的city 天氣字符串
* @param host 請求服務地址
* @param city 得到哪個城市的天氣
* @return
*/
public String getWeatherStr(String host,String city) throws Exception;
/**
* 得到服務器地址
* @return
*/
public String getHost();
/**
* 獲取哪個城市
* @return
*/
public String getCity();
}

 

其中實現方法爲:

public class WeatherAPIImpl implements IWeatherAPI {
/*
* 得到相應城市的天氣
* @see com.otitan.tgs.api.IWeatherAPI#getWeatherStr(java.lang.String, java.lang.String)
*/
@Override
public String getWeatherStr() throws Exception {
return getWeatherStr(getHost(),getCity());
}

/*
* 得到相應城市的天氣
* @see com.otitan.tgs.api.IWeatherAPI#getWeatherStr(java.lang.String, java.lang.String)
*/
@Override
public String getWeatherStr(String host, String city) throws Exception {
try {
InputStream is = WebServiceUtil.get(host+city+”.html”);
String weather = WebServiceUtil.streamToStr(is,”UTF-8″);
is.close();
return weather;
} catch (ClientProtocolException e) {
e.printStackTrace();
Logs.error(“獲取天氣預報接口請求失敗,請確認對方主機是否連接正常”);
throw e;
} catch (URISyntaxException e) {
e.printStackTrace();
throw e;
} catch (IOException e) {
e.printStackTrace();
throw e;
}
}

/*
* 得到請求服務器
* @see com.otitan.tgs.api.IWeatherAPI#getHost()
*/
@Override
public String getHost() {

String host = Util.KONG;
try{
host = Util.loadProperties().getString(“weather_host”);
}catch (Exception e) {
Logs.error(“獲取天氣預報接口主機失敗”);
}
return host;
}

/*
* 得到要請求的城市
* @see com.otitan.tgs.api.IWeatherAPI#getCity()
*/
@Override
public String getCity() {
String city = Util.KONG;
try{
city = Util.loadProperties().getString(“city”);
}catch (Exception e) {
Logs.error(“獲取天氣預報城市失敗”);
}
return city;
}

}

 

其中有一個WebServiceUtil   類,此類的方法如下:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;

public class WebServiceUtil {

/**
* 發送請求
*
* @param url
*            請求服務器
* @param parameters
*            請求參數
* @return inputStream 返回該流後,調用者必須關閉該流
* @throws Exception
*/
public static InputStream post(String url, MultipartEntity parameters)
throws Exception {

HttpClient client = new DefaultHttpClient();
HttpPost postrequest = new HttpPost(url);
try {
if (parameters != null) {
postrequest.setEntity(parameters);
}
HttpResponse postresponse = client.execute(postrequest);
InputStream is = postresponse.getEntity().getContent();
return is;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
throw e;
} catch (ClientProtocolException e) {
e.printStackTrace();
throw e;
} catch (IOException e) {
e.printStackTrace();
throw e;
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
/**
* httpsPost請求
*
* @param url
*            請求服務器
* @param parameters
*            請求參數
* @return inputStream 返回該流後,調用者必須關閉該流
* @throws Exception
*/
public static InputStream httpspost(String url, MultipartEntity parameters)
throws Exception {

HttpClient client = new DefaultHttpClient();
client = wrapClient(client);
HttpPost postrequest = new HttpPost(url);
try {
if (parameters != null) {
postrequest.setEntity(parameters);
}
HttpResponse postresponse = client.execute(postrequest);
InputStream is = postresponse.getEntity().getContent();
return is;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
throw e;
} catch (ClientProtocolException e) {
e.printStackTrace();
throw e;
} catch (IOException e) {
e.printStackTrace();
throw e;
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}

/**
* get 請求
*
* @param url
* @return InputStream
* @throws URISyntaxException
* @throws ClientProtocolException
* @throws IOException
*/
public static InputStream get(String url) throws URISyntaxException,
ClientProtocolException, IOException {
// 定義HttpClient
HttpClient client = new DefaultHttpClient();
// 實例化HTTP方法
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
InputStream is = response.getEntity().getContent();
return is;
}

/**
* httpsget 請求 防止有證書的
*
* @param url
* @return InputStream
* @throws URISyntaxException
* @throws ClientProtocolException
* @throws IOException
*/
public static InputStream httpsget(String url) throws URISyntaxException,
ClientProtocolException, IOException {
// 定義HttpClient
HttpClient client = new DefaultHttpClient();
client = wrapClient(client);
// 實例化HTTP方法
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
InputStream is = response.getEntity().getContent();
return is;
}

/**
* 將流轉換成字符串
*
* @param is
* @param code  字符編碼
* @return 返回字符串之後,必須關閉流
* @throws IOException
*/
public static String streamToStr(InputStream is,String code) throws IOException {
StringBuilder sb = new StringBuilder();
try {
if (is != null) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, code));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
}
return sb.toString();
} catch (IOException e) {
throw e;
}
}

/**
* 獲取可信任https鏈接,以避免不受信任證書出現peer not authenticated異常
*
* @param base
* @return
*/
public static HttpClient wrapClient(HttpClient base) {
try {
SSLContext ctx = SSLContext.getInstance(“TLS”);
X509TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] xcs,
String string) {
}

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

public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx);
ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = base.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme(“https”, ssf, 443));

return new DefaultHttpClient(ccm, base.getParams());
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}

}

 

其中也包括一個Util 類,方法如下:其中的loadProperties  是加載配置文件的方法

public class Util {

public static final String KONG = “”;
public static final String KONGGE = ” “;
public static final String NULL = “null”;
public static final String YEARMONTHDAY = “yyyy-MM-dd”;
public static final String INDEXDATE = “yyyy/MM/dd”;
public static final String HOURMINSECOND = “yyyy-MM-dd HH:mm:ss”;
public static final String DOUHAO = “,”;
public static final int PAGECOUNT = 35;//火車站點用於每頁顯示的數量
/**
* 判斷字符串是否爲空
* @param arg
* @return
*/
public static boolean isEmpty(String arg){
if(arg == null || NULL.equals(arg) || KONG.equals(arg.trim())){
return true;
}else{
return false;
}
}

/**
* 將字符串轉換成時間對象
* @param sourceStr
* @param format
* @return
* @throws ParseException
*/
public static Date strToDate(String sourceStr,String format) throws ParseException{
return new SimpleDateFormat(format).parse(sourceStr);
}

/**
* 將時間類型轉換成相應的字符串
* @param date
* @param format
* @return
*/
public static String dateToStr(Date date,String format){
if(date == null){
return KONG;
}else{
return new SimpleDateFormat(format).format(date);
}
}

/**
* 加載配置文件 config.properties
* @return
*/
public static ResourceBundle loadProperties() {

ResourceBundle rb = ResourceBundle.getBundle(“config”, Locale.getDefault());
return rb;
}

/**
* 將iso字符轉換成utf8
* 用於亂碼
* @param iso
* @return
*/
public static String isoToUtf8(String iso){

if(!isEmpty(iso)){
try {
String utf = new String(iso.getBytes(“ISO8859-1″),”UTF-8″);
return utf;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
Logs.error(“轉換字符錯誤”);
return KONG;
}
}else{
return KONG;
}
}
/**
* main
* @param args
*/
public static void main(String[] args) {
}

/**
* 獲取當前的時間字符串
* @return
*/
public static String getSystemTime() {
return format( new Date(), HOURMINSECOND );
}
/**
* 將指定的時間按照指定的格式轉換爲字符串
* @param d
* @param format
* @return
*/
public static String format( Date d, String format ) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(d);
}
}

 

配置文件:config.properties

###############配置文件##################
#############天氣預報接口配置############
#weather_host=http://www.weather.com.cn/data/sk/
weather_host=http://www.weather.com.cn/data/cityinfo/
#三亞城市代碼
#city=101310201
#北京城市代碼
city=101010100

接下來調用WeatherAPIImpl類的 getWeatherStr()方法,就可以返回天氣預報的字符串,返回的字符串爲一個json對象的字符串,

而前臺拿到json字符串之後,便可以進行解析即可。我是這樣進行解析的:

var weatherObj = eval(json);//json爲返回的天氣字符串
if(weatherObj[0]){

var weather = weatherObj[0].weatherinfo;
var info = weather.weather;//天氣
var hightemp = weather.temp1;//溫度
var lowtemp = weather.temp2;//溫度
var pic = weather.img1;
var css = pic.split(“.gif”)[0];//得到相應的天氣圖標css,然後把中國天氣網的天氣背景圖片下載下來,放到本地用於展示
if(css.length ==2){
var cssfirst = css.substr(0,1);
var csssecond = css.substr(1);
css = cssfirst+”0″+csssecond;
}
$(“#weatherimg”).addClass(“jpg80″).addClass(css);
$(“#weather”).html(info+”  最高溫度:”+hightemp+”  最低溫度”+lowtemp);
}else{
$(“#weather”).html(“天氣接口獲取失敗”);
}

 

以下是自己解析後的css樣式 :
.jpg80 {
background-p_w_picpath: url(“../../img/weather/blue80.jpg”);//該圖片從中國天氣網下載而來
height: 80px;
width: 80px;
}
.d00 {
background-position: 0 0;
}
.d01 {
background-position: -80px 0;
}
.d02 {
background-position: -160px 0;
}
.d03 {
background-position: -240px 0;
}
.d04 {
background-position: -320px 0;
}
.d05 {
background-position: -400px 0;
}
.d06 {
background-position: -480px 0;
}
.d07 {
background-position: -560px 0;
}
.d08 {
background-position: -640px 0;
}
.d09 {
background-position: 0 -80px;
}
.d10 {
background-position: -80px -80px;
}
.d11 {
background-position: -160px -80px;
}
.d12 {
background-position: -240px -80px;
}
.d13 {
background-position: -320px -80px;
}
.d14 {
background-position: -400px -80px;
}
.d15 {
background-position: -480px -80px;
}
.d16 {
background-position: -560px -80px;
}
.d17 {
background-position: -640px -80px;
}
.d18 {
background-position: 0 -160px;
}
.d19 {
background-position: -80px -160px;
}
.d20 {
background-position: -160px -160px;
}
.d21 {
background-position: -240px -160px;
}
.d22 {
background-position: -320px -160px;
}
.d23 {
background-position: -400px -160px;
}
.d24 {
background-position: -480px -160px;
}
.d25 {
background-position: -560px -160px;
}
.d26 {
background-position: -640px -160px;
}
.d27 {
background-position: 0 -240px;
}
.d28 {
background-position: -80px -240px;
}
.d29 {
background-position: -160px -240px;
}
.d30 {
background-position: -240px -240px;
}
.d31 {
background-position: -320px -240px;
}
.d32 {
background-position: -400px -240px;
}
.d33 {
background-position: -480px -240px;
}
.d53 {
background-position: -560px -240px;
}
.n00 {
background-position: 0 -320px;
}
.n01 {
background-position: -80px -320px;
}
.n02 {
background-position: -160px -320px;
}
.n03 {
background-position: -240px -320px;
}
.n04 {
background-position: -320px -320px;
}
.n05 {
background-position: -400px -320px;
}
.n06 {
background-position: -480px -320px;
}
.n07 {
background-position: -560px -320px;
}
.n08 {
background-position: -640px -320px;
}
.n09 {
background-position: 0 -400px;
}
.n10 {
background-position: -80px -400px;
}
.n11 {
background-position: -160px -400px;
}
.n12 {
background-position: -240px -400px;
}
.n13 {
background-position: -320px -400px;
}
.n14 {
background-position: -400px -400px;
}
.n15 {
background-position: -480px -400px;
}
.n16 {
background-position: -560px -400px;
}
.n17 {
background-position: -640px -400px;
}
.n18 {
background-position: 0 -480px;
}
.n19 {
background-position: -80px -480px;
}
.n20 {
background-position: -160px -480px;
}
.n21 {
background-position: -240px -480px;
}
.n22 {
background-position: -320px -480px;
}
.n23 {
background-position: -400px -480px;
}
.n24 {
background-position: -480px -480px;
}
.n25 {
background-position: -560px -480px;
}
.n26 {
background-position: -640px -480px;
}
.n27 {
background-position: 0 -560px;
}
.n28 {
background-position: -80px -560px;
}
.n29 {
background-position: -160px -560px;
}
.n30 {
background-position: -240px -560px;
}
.n31 {
background-position: -320px -560px;
}
.n32 {
background-position: -400px -560px;
}
.n33 {
background-position: -480px -560px;
}
.n53 {
background-position: -560px -560px;
}

最終效果如下圖:

天氣預報樣圖

實現天氣預報接口


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