天气预报简单接口的实现

最近项目需要写了个天气预报接口的实现,这里做个小结,大概分以下几个步骤:

  1、对天气预报请求链接的参数进行替换,即传入我们的参数,主要有两个参数:城市名、哪天

2、通过http请求获取请求返回输入流

3、解析返回输入流,获取我们需要的元素

4、封装解析后的元素,为我们所用


代码的实现如下:

package com.tf.weixin.util;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;


/**
 * 调用新浪天气预报接口工具类
 * @author wangbf
 * @date 2015-11-27
 */
public class SinaWeatherUtil {



/**
* 通过城市名称和时间获取指定某天的天气情况
* @param cityName
* @param day
* @return
*/
public static Map<String, String> getWeatherByCityAndDay(String city, String day) {
// 新浪天气预报请求链接
String requestUrl = "http://php.weather.sina.com.cn/xml.php?city=CITY&password=DJOYnieT8234jlsK&day=DAY";
Map<String, String> weatherMap = new HashMap<String, String>();
String cityName = "";
try {
// 对city进行GBK编码
cityName = URLEncoder.encode(city, "GBK");
String url = requestUrl.replace("CITY", cityName).replace("DAY", day);
// 获取http请求返回的输入流
InputStream is = httpRequest(url);
// 解析接口返回的元素(天气情况)
weatherMap = getWeatherEleMap(is);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return weatherMap;
}

/**
* 发送http请求取得返回的输入流
* @param requestUrl 请求地址
* @return
*/
public static InputStream httpRequest(String requestUrl) {
InputStream inputStream = null;
try {
URL url = new URL(requestUrl);
HttpURLConnection httUrlConnection = (HttpURLConnection) url.openConnection();
httUrlConnection.setDoInput(true);
httUrlConnection.setRequestMethod("GET");
httUrlConnection.connect();
// 获得返回输入流
inputStream = httUrlConnection.getInputStream();
} catch (Exception e) {
e.printStackTrace();
}

return inputStream;
}

/**
* 解析接口返回的元素(天气情况)
* @param iStream
* @return
*/
@SuppressWarnings("unchecked")
public static Map<String, String> getWeatherEleMap(InputStream iStream) {
Map<String, String> map = new HashMap<String, String>();
try {
// 使用dom4j解析xml字符串  
SAXReader reader = new SAXReader();  
Document document;
document = reader.read(iStream);
// 得到xml根元素  
Element root = document.getRootElement();
Element weatherEle = root.element("Weather");
if (weatherEle != null) {
List<Element> elements = weatherEle.elements();
for (Element e : elements) {
map.put(e.getName(), e.getText());
}
}
} catch (DocumentException e) {
e.printStackTrace();

return map;
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值