天气预报简单接口的实现

来源:互联网 发布:日语网络教育 编辑:程序博客网 时间:2024/05/16 17:43

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

  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
原创粉丝点击