`

免费天气预报接口

阅读更多

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

最终效果如下图:

天气预报样图

实现天气预报接口

1
0
分享到:
评论
1 楼 文艺吧网 2017-05-29  
http://www.sojson.com/blog/234.html 这个天气预报的接口不错一直有效!

相关推荐

    免费天气预报接口源代码及文档

    本文将详细讲解“免费天气预报接口源代码及文档”这一主题,主要涵盖天气预报接口的使用、新浪天气预报API的特点以及如何通过Web服务或JavaScript AJAX技术进行数据获取。此外,我们还将探讨接口文档的重要性和扩展...

    国家气象局免费天气预报接口,城市代码(plist文件)

    国家气象局免费天气预报接口,城市代码(plist文件)

    免费天气接口

    描述中的“免费的天气预报接口 希望能对你有所帮助”意味着这个接口是无成本的,并且可能对开发者或项目具有实用性。免费天气预报接口通常是通过HTTP请求发送特定的参数,如城市名或经纬度,然后返回包含天气信息的...

    天气预报接口/weather接口/webservice接口

    "天气预报接口"就是这样一个例子,它提供了一个通过Web Service调用来获取天气信息的途径。标题中的"weather接口"和"webservice接口"都指的是这种基于Web Service技术的接口服务。 Web Service接口通常是基于SOAP...

    js天气预报 js版天气预报接口

    综上所述,实现"js天气预报 js版天气预报接口"项目,需要掌握JavaScript基础、AJAX请求、API接口调用、HTML/CSS页面构建、数据处理及错误处理等技能。通过对这些知识点的理解和实践,你可以构建一个动态的、用户友好...

    免费天气预报 WebService 接口

    ### 免费天气预报 WebService 接口知识点详解 #### 一、概述 本文将详细介绍一个免费提供的天气预报 WebService 接口,该接口由上海思集信息科技有限公司提供。此接口旨在帮助开发者快速集成天气预报功能到自己的...

    获取天气预报API,免费接口,项目下载可运行,Java实现

    标题中的“获取天气预报API,免费接口,项目下载可运行,Java实现”表明这是一个关于使用Java语言开发的天气预报API项目,它提供了免费的API接口,并且已经打包为可直接运行的形式。这样的项目通常对开发者来说是很...

    全国天气预报接口

    全国天气预报接口根据城市名/id查询天气,向开发者提供的准确、稳定、丰富的天气数据云服务。

    asp.net 调用天气预报接口实现天气查寻源码

    在这个场景中,我们讨论的是如何利用ASP.NET技术调用天气预报接口,实现一个天气查询的功能。以下是对这个主题的详细解释: 一、ASP.NET Web API ASP.NET Web API 是ASP.NET框架的一部分,专门设计用来构建RESTful...

    天气预报接口调用示例源码20121213

    天气预报接口调用示例源码 源码描述: 一个天气预报接口调用示例源码 注意: 一、源码用于新手学习交流,默认天气预报城市为义乌天气预报, 如需更改其它城市请修改17行代码: disp_weather("义乌");把义乌替换成别...

    天气预报接口,自动获取

    标题中的“天气预报接口,自动获取”指的是在IT领域中,开发或利用一种服务,能够通过编程方式自动地获取实时的天气信息。这种接口通常由气象服务机构提供,允许开发者通过发送请求并接收响应来获取数据,例如当天的...

    天气预报接口数据

    很好用的 天气预报开发json解析数据接口端

    一个使用HttpClient调用天气预报接口的例程

    在这个例程中,我们将深入探讨如何利用HttpClient来调用一个天气预报接口,并解析返回的JSON数据。以下是一些关键知识点: 1. **HttpClient库**:HttpClient是Apache提供的一个开源库,它允许开发者构建HTTP客户端...

    免费接口天气预报实现全过程

    这一过程涵盖了从寻找合适的天气预报接口,到实际编程实现数据获取和解析,再到最终展示天气信息的完整流程。下面,让我们逐步深入了解这一过程。 首先,我们需要找到一个提供免费天气预报API的提供商。这些提供商...

    java获取谷歌百度天气预报

    3. **天气预报API**:谷歌和百度都提供了天气预报API,允许开发者通过特定的接口获取天气信息。这些API通常需要API密钥,用于身份验证和防止滥用。使用API时,我们需要按照文档中的指示,构造正确的请求URL,并可能...

    天气预报接口文件

    个人整理的中央天气预报,可转换wsdl2java

    HTML5实现好看的天气预报网站源码

    免费的数据接口,数据API,童话故事API,笑话API,名言API,提供免费天气预报接口,各种新闻资讯类、生活服务类、趣味娱乐类、功能应用类、知识问答类、数据智能类等API接口数据提供。兼容手机端和PC网页端。各种...

    天气预报 接口地址,提供天气预报的调用显示

    天气预报 接口地址,提供天气预报的调用显示

    天气预报接口,通过sax 解析接口数据

    本案例主要涉及的是一个天气预报接口,该接口返回的数据格式为XML,我们使用SAX(Simple API for XML)进行解析。接下来,我们将深入探讨天气预报接口、SAX解析以及如何处理XML数据。 首先,天气预报接口是一个API...

    java天气预报源程序接口

    Java天气预报源程序接口是一个专为开发者设计的API,它允许程序员通过编写Java代码来获取并展示实时的天气信息。这个接口提供了丰富的功能,使得开发者能够根据需求自定义天气信息的展示格式,从而满足不同应用场景...

Global site tag (gtag.js) - Google Analytics