免费天气预报接口

以下文章属于原创,转载请标明出处 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-image: 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;
}

最终效果如下图:

天气预报样图

实现天气预报接口

你可能感兴趣的:(天气预报接口,免费天气预报接口)