简介:本文详细讲述了通过Java调用百度天气接口的方法,取得返回的JSON格式的数据,并且通过第三方包解析JSON格式的数据。
通过百度天气API调用网络编程接口接收返回的JSON格式的数据。
关于百度天气接口的详细说明可以参考文章: http://www..com/txw1958/p/baidu-weather-forecast-api.html
使用百度提供的天气接口,也就是通过一个URL访问百度天气服务器,通过给URL可以取得包含天气信息的JSON格式的数据。
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
//根据城市获取天气信息的java代码
//cityName 是你要取得天气信息的城市的中文名字,如“北京”,“深圳”
static String getWeatherInform(String cityName){
//百度天气API
String baiduUrl = "http://api.map.baidu.com/telematics/v3/weather?location=北京&output=json&ak=W69oaDTCfuGwzNwmtVvgWfGH";
StringBuffer strBuf;
try {
//通过浏览器直接访问http://api.map.baidu.com/telematics/v3/weather?location=北京&output=json&ak=5slgyqGDENN7Sy7pw29IUvrZ
//5slgyqGDENN7Sy7pw29IUvrZ 是我自己申请的一个AK(许可码),如果访问不了,可以自己去申请一个新的ak
//百度ak申请地址:http://lbsyun.baidu.com/apiconsole/key
//要访问的地址URL,通过URLEncoder.encode()函数对于中文进行转码
baiduUrl = "http://api.map.baidu.com/telematics/v3/weather?location="+URLEncoder.encode(cityName, "utf-8")+"&output=json&ak=5slgyqGDENN7Sy7pw29IUvrZ";
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
strBuf = new StringBuffer();
try{
URL url = new URL(baiduUrl);
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));//转码。
String line = null;
while ((line = reader.readLine()) != null)
strBuf.append(line + " ");
reader.close();
}catch(MalformedURLException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
return strBuf.toString();
}
上面调用百度天气接口的函数返回的JSON格式的数据如下:
{"error":0,"status":"success","date":"2014-08-27","results":[{"currentCity":"北京","pm25":"89","index":[{"title":"穿衣","zs":"炎热","tipt":"穿衣指数","des":"天气炎热,建议着短衫、短裙、短裤、薄型T恤衫等清凉夏季服装。"},{"title":"洗车","zs":"较适宜"