简介:本文详细讲述了通过Java调用百度天气接口的方法,取得返回的JSON格式的数据,并且通过第三方包解析JSON格式的数据。
通过百度天气API调用网络编程接口接收返回的JSON格式的数据。
关于百度天气接口的详细说明可以参考文章: http://www.cnblogs.com/txw1958/p/baidu-weather-forecast-api.html
使用百度提供的天气接口,也就是通过一个URL访问百度天气服务器,通过给URL可以取得包含天气信息的JSON格式的数据。
<pre name="code" class="java">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":"较适宜","tipt":"洗车指数","des":"较适宜洗车,未来一天无雨,风力较小,擦洗一新的汽车至少能保持一天。"},{"title":"旅游","zs":"较适宜","tipt":"旅游指数","des":"天气较好,温度较高,天气较热,但有微风相伴,还是比较适宜旅游的,不过外出时要注意防暑防晒哦!"},{"title":"感冒","zs":"少发","tipt":"感冒指数","des":"各项气象条件适宜,发生感冒机率较低。但请避免长期处于空调房间中,以防感冒。"},{"title":"运动","zs":"较适宜","tipt":"运动指数","des":"天气较好,户外运动请注意防晒。推荐您进行室内运动。"},{"title":"紫外线强度","zs":"中等","tipt":"紫外线强度指数","des":"属中等强度紫外线辐射天气,外出时建议涂擦SPF高于15、PA+的防晒护肤品,戴帽子、太阳镜。"}],"weather_data":[{"date":"周三 08月27日 (实时:29℃)","dayPictureUrl":"http://api.map.baidu.com/images/weather/day/duoyun.png","nightPictureUrl":"http://api.map.baidu.com/images/weather/night/duoyun.png","weather":"多云","wind":"微风","temperature":"33 ~ 20℃"},{"date":"周四","dayPictureUrl":"http://api.map.baidu.com/images/weather/day/leizhenyu.png","nightPictureUrl":"http://api.map.baidu.com/images/weather/night/zhenyu.png","weather":"雷阵雨转阵雨","wind":"微风","temperature":"28 ~ 19℃"},{"date":"周五","dayPictureUrl":"http://api.map.baidu.com/images/weather/day/duoyun.png","nightPictureUrl":"http://api.map.baidu.com/images/weather/night/duoyun.png","weather":"多云","wind":"微风","temperature":"29 ~ 20℃"},{"date":"周六","dayPictureUrl":"http://api.map.baidu.com/images/weather/day/duoyun.png","nightPictureUrl":"http://api.map.baidu.com/images/weather/night/yin.png","weather":"多云转阴","wind":"微风","temperature":"29 ~ 20℃"}]}]}
现在需要对该JSON格式的数据进行解析。
上面返回的JSON格式的数据包含四天的天气信息。现在对JSON格式的数据进行解析。
//需要导入解析JSON格式数据的第三方包 请百度搜索并下载,导入“jsonlib.rar”包
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
//解析JSON数据 要解析的JSON数据:strPar
//WeatherInf 是自己定义的承载所有的天气信息的实体类,包含了四天的天气信息。详细定义见后面。
static WeatherInf resolveWeatherInf(String strPar){
JSONObject dataOfJson = JSONObject.fromObject(strPar);
if(dataOfJson.getInt("error")!=0){
return null;
}
//保存全部的天气信息。
WeatherInf weatherInf = new WeatherInf();
//从json数据中取得的时间�?
String date = dataOfJson.getString("date");
int year = Integer.parseInt(date.substring(0, 4));
int month = Integer.parseInt(date.substring(5, 7));
int day = Integer.parseInt(date.substring(8, 10));
Date today = new Date(year-1900,month-1,day);
JSONArray results=dataOfJson.getJSONArray("results");
JSONObject results0=results.getJSONObject(0);
String location = results0.getString("currentCity");
int pmTwoPointFive;
if(results0.getString("pm25").isEmpty()){
pmTwoPointFive = 0;
}else{
pmTwoPointFive = results0.getInt("pm25");
}
//System.out.println(results0.get("pm25").toString()+"11");
try{
JSONArray index = results0.getJSONArray("index");
JSONObject index0 = index.getJSONObject(0);//穿衣
JSONObject index1 = index.getJSONObject(1);//洗车
JSONObject index2 = index.getJSONObject(2);//感冒
JSONObject index3 = index.getJSONObject(3);//运动
JSONObject index4 = index.getJSONObject(4);//紫外线强度
String dressAdvise = index0.getString("des");//穿衣建议
String washCarAdvise = index1.getString("des");//洗车建议
String coldAdvise = index2.getString("des");//感冒建议
String sportsAdvise = index3.getString("des");//运动建议
String ultravioletRaysAdvise = index4.getString("des");//紫外线建议
weatherInf.setDressAdvise(dressAdvise);
weatherInf.setWashCarAdvise(washCarAdvise);
weatherInf.setColdAdvise(coldAdvise);
weatherInf.setSportsAdvise(sportsAdvise);
weatherInf.setUltravioletRaysAdvise(ultravioletRaysAdvise);
}catch(JSONException jsonExp){
weatherInf.setDressAdvise("要温度,也要风度。天热缓减衣,天凉及添衣!");
weatherInf.setWashCarAdvise("你洗还是不洗,灰尘都在哪里,不增不减。");
weatherInf.setColdAdvise("一天一个苹果,感冒不来找我!多吃水果和蔬菜。");
weatherInf.setSportsAdvise("生命在于运动!不要总宅在家里哦!");
weatherInf.setUltravioletRaysAdvise("心灵可以永远年轻,皮肤也一样可以!");
}
JSONArray weather_data = results0.getJSONArray("weather_data");//weather_data中有四项�?
//OneDayWeatherInf是自己定义的承载某一天的天气信息的实体类,详细定义见后面。
OneDayWeatherInf[] oneDayWeatherInfS = new OneDayWeatherInf[4];
for(int i=0;i<4;i++){
oneDayWeatherInfS[i] = new OneDayWeatherInf();
}
for(int i=0;i<weather_data.size();i++){
JSONObject OneDayWeatherinfo=weather_data.getJSONObject(i);
String dayData = OneDayWeatherinfo.getString("date");
OneDayWeatherInf oneDayWeatherInf = new OneDayWeatherInf();
oneDayWeatherInf.setDate((today.getYear()+1900)+"."+(today.getMonth()+1)+"."+today.getDate());
today.setDate(today.getDate()+1);//增加一天
oneDayWeatherInf.setLocation(location);
oneDayWeatherInf.setPmTwoPointFive(pmTwoPointFive);
if(i==0){//第一个,也就是当天的天气,在date字段中最后包含了实时天气
int beginIndex = dayData.indexOf(":");
int endIndex = dayData.indexOf(")");
if(beginIndex>-1){
oneDayWeatherInf.setTempertureNow(dayData.substring(beginIndex+1, endIndex));
oneDayWeatherInf.setWeek(OneDayWeatherinfo.getString("date").substring(0,2));
}else{
oneDayWeatherInf.setTempertureNow(" ");
oneDayWeatherInf.setWeek(OneDayWeatherinfo.getString("date").substring(0,2));
}
}else{
oneDayWeatherInf.setWeek(OneDayWeatherinfo.getString("date"));
}
oneDayWeatherInf.setTempertureOfDay(OneDayWeatherinfo.getString("temperature"));
oneDayWeatherInf.setWeather(<span style="font-family: Arial, Helvetica, sans-serif;">OneDayWeatherinfo.getString("weather")</span><span style="font-family: Arial, Helvetica, sans-serif;">);</span>
oneDayWeatherInf.setWeather(weather);
oneDayWeatherInf.setWind(OneDayWeatherinfo.getString("wind"));
oneDayWeatherInfS[i] = oneDayWeatherInf;
}
weatherInf.setWeatherInfs(oneDayWeatherInfS);
return weatherInf;
}
现在就将JSON格式的数据提取出来放到Java中的实体类中了。
附1:
<pre name="code" class="java">//WeatherInf 是自己定义的承载所有的天气信息的实体类,包含了四天的天气信息。
public class WeatherInf {
private OneDayWeatherInf[] weatherInfs;
private String dressAdvise;//穿衣建议
private String washCarAdvise;//洗车建议
private String coldAdvise;//感冒建议
private String sportsAdvise;//运动建议
private String ultravioletRaysAdvise;//紫外线建议
public WeatherInf(){
dressAdvise = "";
washCarAdvise = "";
coldAdvise = "";
sportsAdvise = "";
ultravioletRaysAdvise = "";
}
public void printInf(){
System.out.println(dressAdvise);
System.out.println(washCarAdvise);
System.out.println(coldAdvise);
System.out.println(sportsAdvise);
System.out.println(ultravioletRaysAdvise);
for(int i=0;i<weatherInfs.length;i++){
System.out.println(weatherInfs[i]);
}
}
public OneDayWeatherInf[] getWeatherInfs() {
return weatherInfs;
}
public void setWeatherInfs(OneDayWeatherInf[] weatherInfs) {
this.weatherInfs = weatherInfs;
}
public String getDressAdvise() {
return dressAdvise;
}
public void setDressAdvise(String dressAdvise) {
this.dressAdvise = dressAdvise;
}
public String getWashCarAdvise() {
return washCarAdvise;
}
public void setWashCarAdvise(String washCarAdvise) {
this.washCarAdvise = washCarAdvise;
}
public String getColdAdvise() {
return coldAdvise;
}
public void setColdAdvise(String coldAdvise) {
this.coldAdvise = coldAdvise;
}
public String getSportsAdvise() {
return sportsAdvise;
}
public void setSportsAdvise(String sportsAdvise) {
this.sportsAdvise = sportsAdvise;
}
public String getUltravioletRaysAdvise() {
return ultravioletRaysAdvise;
}
public void setUltravioletRaysAdvise(String ultravioletRaysAdvise) {
this.ultravioletRaysAdvise = ultravioletRaysAdvise;
}
}
<pre name="code" class="java">//OneDayWeatherInf是自己定义的承载某一天的天气信息的实体类
public class OneDayWeatherInf {
private
String location;
String date;
String week;
String tempertureOfDay;
String tempertureNow;
String wind;
String weather;
String picture;
int pmTwoPointFive;
public OneDayWeatherInf(){
location = "";
date = "";
week = "";
tempertureOfDay = "";
tempertureNow = "";
wind = "";
weather = "";
picture = "undefined";
pmTwoPointFive = 0;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getWeek() {
return week;
}
public void setWeek(String week) {
this.week = week;
}
public String getTempertureOfDay() {
return tempertureOfDay;
}
public void setTempertureOfDay(String tempertureOfDay) {
this.tempertureOfDay = tempertureOfDay;
}
public String getTempertureNow() {
return tempertureNow;
}
public void setTempertureNow(String tempertureNow) {
this.tempertureNow = tempertureNow;
}
public String getWind() {
return wind;
}
public void setWind(String wind) {
this.wind = wind;
}
public String getWeather() {
return weather;
}
public void setWeather(String weather) {
this.weather = weather;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
public int getPmTwoPointFive() {
return pmTwoPointFive;
}
public void setPmTwoPointFive(int pmTwoPointFive) {
this.pmTwoPointFive = pmTwoPointFive;
}
public String toString(){
return location+" "+date+" "+week+" tempertureOfDay: "+tempertureOfDay+" tempertureNow: "+tempertureNow+" "+wind+" "+weather+" "+picture+" "+pmTwoPointFive;
}
}