(1)程序查询结果图(图中较下的图是百度查询天气的结果)
(2)http://developer.baidu.com/map/carapi-7.htm 百度车联网接口说明中有天气查询的接口,目前是免费提供的(一天可以查询5000次)
下表是接口返回的json数据。(表中##及后内容是为了方便的查看数据填写的)
{'date': '2015-03-24', 'error': 0, ##&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&begin results 'results': [ { 'pm25': '95', ##////////////////////////////////////////////////////////begin index 'index': [ {'des': '建议着厚外套加毛衣等服装。年老体弱者宜着大衣、呢外套加羊毛衫。', 'tipt': '穿衣指数', 'zs': '较冷', 'title': '穿衣'}, {'des': '较适宜洗车,未来一天无雨,风力较小,擦洗一新的汽车至少能保持一天。', 'tipt': '洗车指数', 'zs': '较适宜', 'title': '洗车'}, {'des': '天气较好,风稍大,但温度适宜,是个好天气哦。适宜旅游,您可以尽情地享受大自然的无限风光。', 'tipt': '旅游指数', 'zs': '适宜', 'title': '旅游'}, {'des': '昼夜温差较大,较易发生感冒,请适当增减衣服。体质较弱的朋友请注意防护。', 'tipt': '感冒指数', 'zs': '较易发', 'title': '感冒'}, {'des': '天气较好,但因风力稍强,户外可选择对风力要求不高的运动,推荐您进行室内运动。', 'tipt': '运动指数', 'zs': '较适宜', 'title': '运动'}, {'des': '属中等强度紫外线辐射天气,外出时建议涂擦SPF高于15、PA+的防晒护肤品,戴帽子、太阳镜。', 'tipt': '紫外线强度指数', 'zs': '中等', 'title': '紫外线强度'} ], ##///////////////////////////////////////////////////////end index ##..........................................................begin weather_data 今天起的4天气候 'weather_data': [ {'nightPictureUrl': 'http://api.map.baidu.com/images/weather/night/qing.png', 'weather': '晴', 'temperature': '3℃', 'date': '周二 03月24日 (实时:15℃)', 'wind': '微风', 'dayPictureUrl': 'http://api.map.baidu.com/images/weather/day/qing.png'}, {'nightPictureUrl': 'http://api.map.baidu.com/images/weather/night/qing.png', 'weather': '晴', 'temperature': '18 ~ 6℃', 'date': '周三', 'wind': '南风3-4级', 'dayPictureUrl': 'http://api.map.baidu.com/images/weather/day/qing.png'}, {'nightPictureUrl': 'http://api.map.baidu.com/images/weather/night/qing.png', 'weather': '晴', 'temperature': '20 ~ 8℃', 'date': '周四', 'wind': '微风', 'dayPictureUrl': 'http://api.map.baidu.com/images/weather/day/qing.png'}, {'nightPictureUrl': 'http://api.map.baidu.com/images/weather/night/yin.png', 'weather': '多云转阴', 'temperature': '22 ~ 10℃', 'date': '周五', 'wind': '南风3-4级', 'dayPictureUrl': 'http://api.map.baidu.com/images/weather/day/duoyun.png'} ], ##............................................................end weather_data 'currentCity': '北京'} ], ##&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&end results 'status': 'success' } |
import json
import urllib.request import urllib.parse url0 = 'http://api.map.baidu.com/telematics/v3/weather' url ='http://api.map.baidu.com/telematics/v3/weather?location=北京&output=json&ak=yourkey' url1 ='https://www.python.org/' ###最简单的方式 ##response = urllib.request.urlopen(url1) ##buff = response.read() ##html = buff.decode('utf8') ##response.close()#记得关闭 ##print(html) ###使用Request的方式,这种方式同样可以用来处理其他URL,例如FTP: ##import urllib.request ##req = urllib.request.Request(url1) ##response = urllib.request.urlopen(req) ##buff = response.read() ###显示 ##the_page = buff.decode('utf8') ##response.close() ##print(the_page) #使用GET请求 #例子中用到百度车联网中提供的天气查询api接口: #http://api.map.baidu.com/telematics/v3/weather?location=北京&output=json&ak=yourkey #http://api.map.baidu.com/telematics/v3/weather?location=北京&output=json&ak=yourkey #decode('gb2312') name1=input('请输入城市:') #url1 = 'http://api.map.baidu.com/telematics/v3/weather?location='+name1+'&output=json&ak=yourkey' #print(url1) data = {'location':name1, 'output':'json', 'ak':'RehcDwqFhr77yNTZVGKPA45U'}#ak后面的值是我在百度上申请的key url_values = urllib.parse.urlencode(data) full_url = url0 + '?' + url_values #print(full_url) f = urllib.request.urlopen(full_url) weatherHTML= f.read().decode('utf-8')#读入打开的url weatherJSON = json.JSONDecoder().decode(weatherHTML)#创建json #print(weatherHTML) #print(weatherJSON) print('========================') results = weatherJSON['results'] print("当前城市:",results[0]['currentCity']) #当天的天气建议 index = results[0]['index'] for each_index in index: print(each_index['title'],":",each_index['zs']) weather_data =results[0]['weather_data'] for each_data in weather_data: print("时间:%s 天气:%s 温度:%s 风力:%s" %(each_data['date'],each_data['weather'],each_data['temperature'],each_data['wind'])) import os os.system('pause')
</pre><pre name="code" class="python">。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
{"error": 0, "status": "success","date": "2014-05-10",
"results": [
{ "currentCity": "南京",
"weather_data": [
{"date": "周六(今天, 实时:19℃)","dayPictureUrl": "http://api.map.baidu.com/images/weather/day/dayu.png","nightPictureUrl": "http://api.map.baidu.com/images/weather/night/dayu.png",<span style="font-family: Arial, Helvetica, sans-serif;"> "weather": "大雨", "wind": "东南风5-6级", "temperature": "18℃" },</span>
<span style="font-family: Arial, Helvetica, sans-serif;"> { "date": "周日", "dayPictureUrl": "http://api.map.baidu.com/images/weather/day/zhenyu.png", "nightPictureUrl": "http://api.map.baidu.com/images/weather/night/duoyun.png", "weather": "阵雨转多云", "wind": "西北风4-5级", "temperature": "21 ~ 14℃"}</span>
<span style="font-family: Arial, Helvetica, sans-serif;"> ] </span>
<span style="font-family: Arial, Helvetica, sans-serif;">} </span>
<span style="font-family: Arial, Helvetica, sans-serif;">]</span>
<span style="font-family: Arial, Helvetica, sans-serif;">}</span>
gson将String解析成对应类时,类里面的属性名必须跟Json字段里面的Key是一模一样的;内部嵌套的用[]括起来的部分是一个List,所以定义为 public List<B> b,而只用{}嵌套的就定义为 public C c,<span style="font-family: Arial, Helvetica, sans-serif;">所以,上面的json数据,分解为如下三个类。</span>
第一、WeatherInfo
package com.example.httptest;
import java.util.List;
public class WeatherInfo
{
private String error;
private String status;
private String date;
private List<Results> results;
public String getError()
{
return error;
}
public void setError(String error)
{
this.error = error;
}
public String getStatus()
{
return status;
}
public void setStatus(String status)
{
this.status = status;
}
public String getDate()
{
return date;
}
public void setDate(String date)
{
this.date = date;
}
public List<Results> getResults()
{
return results;
}
public void setResults(List<Results> results)
{
this.results = results;
}
@Override
public String toString()
{
return "Status [error=" + error + ", status=" + status
+ ", date=" + date + ", results=" + results + "]";
}
}
第二、Results
package com.example.httptest;
import java.util.List;
public class Results
{
private String currentCity;
private List<Weather> weather_data;
public String getCurrentCity()
{
return currentCity;
}
public void setCurrentCity(String currentCity)
{
this.currentCity = currentCity;
}
public List<Weather> getWeather_data()
{
return weather_data;
}
public void setWeather_data(List<Weather> weather_data)
{
this.weather_data = weather_data;
}
@Override
public String toString()
{
return "Results [currentCity=" + currentCity + ", weather_data="
+ weather_data + "]";
}
}
第三、Weather
package com.example.httptest;
public class Weather {
private String date;
private String dayPictureUrl;
private String nightPictureUrl;
private String weather;
private String wind;
private String temperature;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getDayPictureUrl() {
return dayPictureUrl;
}
public void setDayPictureUrl(String dayPictureUrl) {
this.dayPictureUrl = dayPictureUrl;
}
public String getNightPictureUrl() {
return nightPictureUrl;
}
public void setNightPictureUrl(String nightPictureUrl) {
this.nightPictureUrl = nightPictureUrl;
}
public String getWeather() {
return weather;
}
public void setWeather(String weather) {
this.weather = weather;
}
public String getWind() {
return wind;
}
public void setWind(String wind) {
this.wind = wind;
}
public String getTemperature() {
return temperature;
}
public void setTemperature(String temperature) {
this.temperature = temperature;
}
@Override
public String toString() {
return "Weather [date=" + date + ", dayPictureUrl="
+ dayPictureUrl + ", nightPictureUrl="
+ nightPictureUrl + ", weather=" + weather
+ ", wind=" + wind + ", temperature=" + temperature
+ "]";
}
}
用异步类调用获取天气信息
package com.example.httptest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import com.google.gson.Gson;
import android.os.AsyncTask;
import android.util.Log;
public class MyAsyn extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... arg0) {
// TODO 自动生成的方法存根
String url ="http://api.map.baidu.com/telematics/v3/weather?location=%E9%BE%99%E6%B5%B7&output=json&ak=RehcDwqFhr77yNTZVGKPA45U";
// 生成请求对象
HttpGet httpGet = new HttpGet(url);
HttpClient httpClient = new DefaultHttpClient();
// 发送请求
try
{
BufferedReader in = null;
HttpResponse response = httpClient.execute(httpGet);
Gson gson = new Gson();
String rString = EntityUtils.toString(response.getEntity());
com.example.httptest.WeatherInfo weatherInfo=gson.fromJson(rString, com.example.httptest.WeatherInfo.class);//这样就可以获取所要的数据类。
Log.e("weatherInfo",weatherInfo.toString());
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while((line = in.readLine()) != null){
sb.append(line + NL);
}
in.close();
String page = sb.toString();
Log.e("test", page);
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO 自动生成的方法存根
super.onPostExecute(result);
}
}