TIME:2020年7月6日
和风天气API使用方法:
1、申请天气接口
2、天气接口账号初始化
3、选择服务模式,免费还是商业版
4、通过URL请求数据(get和post方式)并接收数据
5、解析JSON数据
step1 申请天气接口
step2 天气接口初始化
HeConfig.init(publicId,key);
step3 选择服务模式
//切换到免费服务模式
HeConfig.switchToFreeServerNode();
step4 通过URL请求数据
private void queryWeather() {
new Thread() {
@Override
public void run() {
String param = "key=07a717828d9f49169062e88e66d50697&location=auto_ip";
StringBuilder sb = new StringBuilder();
InputStream is = null;
BufferedReader br = null;
PrintWriter out = null;
try {
String url = "https://free-api.heweather.net/s6/weather";
URL uri = new URL(url);
HttpURLConnection connection = (HttpURLConnection) uri.openConnection();//开启一个url的连接,用HttpURLConnection连接方式处理
connection.setRequestMethod("POST");//设置连接对象的请求数据的方式
connection.setConnectTimeout(3000);//设置连接对象的请求超时的时间
connection.setReadTimeout(5000);//设置读超时
connection.setRequestProperty("accept", "*/*");
//发送参数
connection.setDoOutput(true);
out = new PrintWriter(connection.getOutputStream());
out.print(param);
Log.e("param",param);
out.flush();
//接收结果
is = connection.getInputStream();
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
//缓冲逐行读取
String line;
while ( ( line = br.readLine() ) != null ) {
sb.append(line);
}
queryWeather2();
Log.e("success","tmp:" + sb.toString());
} catch (Exception ignored) {
} finally {
//关闭流
try {
if(is!=null){
is.close();
}
if(br!=null){
br.close();
}
if (out!=null){
out.close();
}
} catch ( Exception ignored ) {}
}
}
}.start();
}
step5解析JSON数据
以实况天气为例
public void queryWeather2() {
/**
* 实况天气
* 实况天气即为当前时间点的天气状况以及温湿风压等气象指数,具体包含的数据:体感温度、
* 实测温度、天气状况、风力、风速、风向、相对湿度、大气压强、降水量、能见度等。
*
* @param context 上下文
* @param location 地址详解
* @param lang 多语言,默认为简体中文,海外城市默认为英文
* @param unit 单位选择,公制(m)或英制(i),默认为公制单位
* @param listener 网络访问回调接口
*/
HeWeather.getWeatherNow(Weather.this, "CN101080101",Lang.CHINESE_SIMPLIFIED, Unit.METRIC, new HeWeather.OnResultWeatherNowBeanListener() {
@Override
public void onError(Throwable e) {
Log.i(TAG, "Weather Now onError: ", e);
}
@Override
public void onSuccess(Now dataObject) {
Log.i(TAG, " Weather Now onSuccess: " + new Gson().toJson(dataObject));
//先判断返回的status是否正确,当status正确时获取数据,若status不正确,可查看status对应的Code值找到原因
if (Code.OK.getCode().equalsIgnoreCase(dataObject.getStatus())) {
//此时返回数据
Basic basic = dataObject.getBasic();
String location = basic.getLocation();
NowBase now = dataObject.getNow();
String tmp = now.getTmp();
Intent intent = new Intent();
intent.putExtra("tmp", tmp);
intent.setAction("number_tmp");
sendBroadcast(intent);
} else {
//在此查看返回数据失败的原因
String status = dataObject.getStatus();
Code code = Code.toEnum(status);
Log.i(TAG, "failed code: " + code);
}
}
});
}