调用接口,首先得去注册一个账号,(它只能获取当天的数据,没有百度API的功能强大)
官网参考:http://www.yytianqi.com/api.html
package com.common.filo;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class weatherApi {
public static void main(String[] args) {
//31.874000,101.110880,3362.300
String weidu = "101.110880";
String jindu = "31.874000";
String weatherData = getWeatherData(weidu,jindu);
List getWeather = GetWeather(weatherData);
for (Object object : getWeather) {
System.out.println(object.toString());
}
}
/**
* 根据经纬度获取城市的气温信息
* @param weidu 纬度
* @param jindu 经度
* @return
*/
public static String getWeatherData(String weidu,String jindu) {
StringBuilder sb = new StringBuilder();
//http://api.yytianqi.com/weatherhours?key=xxxx&city=31.874000,101.110880"
try {
String weather_url = "http://api.yytianqi.com/weatherhours?key=bopi3li1ip93ae0n&city="+weidu+","+jindu+"";
URL url = new URL(weather_url);
URLConnection conn = url.openConnection();
InputStream inputStream = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"utf-8");
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = null;
while((line=reader.readLine())!=null) {
sb.append(line+" ");
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
/**
* 对调用天气API的数据进行json序列化
* @param weatherJson
* @return
*/
public static List<String> GetWeather(String weatherJson) {
//城市名
String cityname= "";
//获取当时的气温
String qw = "";
List<String> list = new ArrayList<String>();
JSONObject dataJson = JSONObject.fromObject(weatherJson.trim());
String getCode = dataJson.getString("msg");
//如果没有获取到信息,则返回未知
if(getCode.equals("Error")) {
cityname = "未知";
qw = "未知";
list.add(cityname);
list.add(qw);
return list;
}else {
String data = dataJson.getString("data");
dataJson = JSONObject.fromObject(data);
cityname = dataJson.getString("cityName");
JSONArray qwlist = dataJson.getJSONArray("list");
JSONObject result = qwlist.getJSONObject(0);
qw = result.getString("qw");
qw = qw+"℃";
list.add(cityname);
list.add(qw);
}
return list;
}
}
返回结果为JSON格式
{
"code": 1,
"msg": "Sucess",
"counts": 2362, //访问的剩余次数。
"data": {
"cityId": "CH010100", //城市id
"cityName": "北京", //城市名称
"lastUpdate": "2016-03-09 17:10:00", //实况更新时间
"tq": "多云", //天气现象
"numtq": "01", //天气现象编码
"qw": "5.0", //当前气温
"fl": "微风", //当前风力
"numfl": "0", //当前风力编码
"fx": "无持续风向", //当前风向
"numfx": "0", //当前风向编码
"sd": "10.0" //相对湿度,直接在此数值后添加%即可
}
}
标签:Java,String,qw,java,IP,list,天气,dataJson,import From: https://www.cnblogs.com/mask-xiexie/p/16802159.html