[学习笔记]如何调用百度天气api,学习自百度api

本文介绍了一个使用Struts框架调用第三方天气API的例子,通过GET请求获取JSON格式的天气数据,并将结果返回给前端展示。

使用的是struts框架,调用结果返回出weatherResult【json格式】,再传到前台

public String getWeather() {

System.out.println("hello weather");
BufferedReader reader = null;
StringBuffer sbf = new StringBuffer();
String httpUrl = "http://apis.baidu.com/apix/idauth/idauth" + "?" + "name=刘坤&cardno=320921199108025071";
try {
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestMethod("GET");
// 填入apikey到HTTP header
connection.setRequestProperty("apikey",
"3286167d75112ab25de8936c7a270b35");
connection.connect();
InputStream is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
weatherResult = sbf.toString();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(weatherResult);
return SUCCESS;

}

json数据示例:

{
    "HeWeather data service 3.0": [{

        "status": "ok",    //接口状态,参考http://www.heweather.com/documents/api 

        "basic": { //基本信息
            "city": "故宫博物院",  //景点名称
            "cnty": "中国",  //国家
            "id": "CN10101010018A",  //景点ID,参见http://www.heweather.com/documents/cn-attractions-list
            "lat": "116.39",  //城市维度
            "lon": "39.91",  //城市经度
            "update": { //更新时间,景点天气每天更新三次,分别为8、15、18点
                "loc": "2015-07-02 08:10",  //当地时间,如无特殊说明,以下时间均为当地时间
                "utc": "2015-07-02 00:10" //UTC时间
            }
        },

        "daily_forecast": [ //7天预报
        {
            "date": "2015-10-10",  //预报日期,第一天
            "astro": { //天文数值  
                "sr": "06:19",  //日出时间
                "ss": "17:43" //日落时间
            },
            "cond": { //天气状况,天气状况代码和图标,参考http://www.heweather.com/documents/condition-code
                "code_d": "101",  //白天天气状况代码
                "code_n": "101",  //夜间天气状况代码
                "txt_d": "多云",  //白天天气状况描述
                "txt_n": "多云" //夜间天气状况描述
            },
            "tmp": { //温度
                "max": "16",  //最高温度
                "min": "10" //最低温度
            },
            "wind": {   //风力风向
                "dir": "北风",  //风向
                "sc": "3-4"  //风力
            }
        },
       {......}//第二到第七天重复以上内容,略
        ]
    }
  ]
}
本本参考http://apistore.baidu.com/apiworks/servicedetail/880.html,勿喷

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值