腾讯云API获取天气(收费)
package com.vxdata.cases.common.utils;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.vxdata.common.utils.StringUtils;
import sun.misc.BASE64Encoder;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;
public class WeatherUtil {
private static final String FIELD_SECRET_ID = "";//填写secretId
private static final String FIELD_SECRET_KEY = "";//填写secretKey
private static final String FIELD_TENCENT_CLOUD_API = "https://service-is751ged-1257101137.ap-shanghai.apigateway.myqcloud.com/release/weather/query";
public JSONObject getWeather(String log, String lat) {
if (StringUtils.isNotEmpty(log) && StringUtils.isNotEmpty(lat)) {
String weatherInfo = "";
try {
weatherInfo = getWeatherInfo(log, lat);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
JSONObject jsonObject1 = JSONObject.parseObject(weatherInfo);
return jsonObject1;
}
return null;
}
/**
* @param log 经度
* @param lat 纬度
* @return
*/
public static String getWeatherInfo(String log, String lat) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
//云市场分配的密钥Id
String secretId = FIELD_SECRET_ID;
//云市场分配的密钥Key
String secretKey = FIELD_SECRET_KEY;
// url参数拼接
String url = FIELD_TENCENT_CLOUD_API;
String source = "market";
Calendar cd = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
String datetime = sdf.format(cd.getTime());
// 签名
String auth = calcAuthorization(source, secretId, secretKey, datetime);
// 请求方法
String method = "GET";
// 请求头
Map<String, String> headers = new HashMap<String, String>();
headers.put("X-Source", source);
headers.put("X-Date", datetime);
headers.put("Authorization", auth);
// 查询参数
Map<String, String> queryParams = new HashMap<String, String>();
queryParams.put("city",""); //城市名
queryParams.put("citycode",""); // 城市编码
queryParams.put("cityid",""); // 城市id
queryParams.put("ip","");
queryParams.put("location", lat + "," + log); // 纬度 + 经度
// body参数
Map<String, String> bodyParams = new HashMap<String, String>();
if (!queryParams.isEmpty()) {
url += "?" + urlencode(queryParams);
}
String result = "";
BufferedReader in = null;
try {
URL realUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.setRequestMethod(method);
// request headers
for (Map.Entry<String, String> entry : headers.entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
// request body
Map<String, Boolean> methods = new HashMap<>();
methods.put("POST", true);
methods.put("PUT", true);
methods.put("PATCH", true);
Boolean hasBody = methods.get(method);
if (hasBody != null) {
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setDoOutput(true);
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(urlencode(bodyParams));
out.flush();
out.close();
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
public static String calcAuthorization(String source, String secretId, String secretKey, String datetime)
throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
String signStr = "x-date: " + datetime + "\n" + "x-source: " + source;
Mac mac = Mac.getInstance("HmacSHA1");
Key sKey = new SecretKeySpec(secretKey.getBytes("UTF-8"), mac.getAlgorithm());
mac.init(sKey);
byte[] hash = mac.doFinal(signStr.getBytes("UTF-8"));
String sig = new BASE64Encoder().encode(hash);
String auth = "hmac id=\"" + secretId + "\", algorithm=\"hmac-sha1\", headers=\"x-date x-source\", signature=\"" + sig + "\"";
return auth;
}
public static String urlencode(Map<?, ?> map) throws UnsupportedEncodingException {
StringBuilder sb = new StringBuilder();
for (Map.Entry<?, ?> entry : map.entrySet()) {
if (sb.length() > 0) {
sb.append("&");
}
sb.append(String.format("%s=%s",
URLEncoder.encode(entry.getKey().toString(), "UTF-8"),
URLEncoder.encode(entry.getValue().toString(), "UTF-8")
));
}
return sb.toString();
}
public static void main(String[] args) {
WeatherUtil weatherUtil = new WeatherUtil();
JSONObject weather = weatherUtil.getWeather("经度", "纬度");
System.out.println(weather);
}
}
执行结果:
国家气象局API获取实时天气(免费)
import net.sf.json.JSONObject;
import java.io.*;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
public class Weather {
/**
* 国家气象局获取实时天气
* @param Cityid
* @return
* @throws IOException
* @throws NullPointerException
*/
public static Map<String, Object> getTodayWeather2(String Cityid)
throws IOException, NullPointerException {
// 连接中央气象台的API
URL url = new URL("http://www.weather.com.cn/data/cityinfo/" + Cityid
+ ".html");
URLConnection connectionData = url.openConnection();
connectionData.setConnectTimeout(1000);
Map<String, Object> map = new HashMap<String, Object>();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(
connectionData.getInputStream(), "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null)
sb.append(line);
String datas = sb.toString();
System.out.println(datas);
JSONObject jsonData = JSONObject.fromObject(datas);
JSONObject info = jsonData.getJSONObject("weatherinfo");
map.put("city", info.getString("city").toString());// 城市
map.put("temp1", info.getString("temp1").toString());// 最高温度
map.put("temp2", info.getString("temp2").toString());// 最低温度
map.put("weather", info.getString("weather").toString());//天气
map.put("ptime", info.getString("ptime").toString());// 发布时间
} catch (SocketTimeoutException e) {
System.out.println("连接超时");
} catch (FileNotFoundException e) {
System.out.println("加载文件出错");
}
return map;
}
public static void main(String[] args) {
try {
//测试获取实时天气2(包含天气,温度范围)
Map<String, Object> map2 = getTodayWeather2("101190401"); //这块填的是城市编码
System.out.println(map2.get("city") + "\t" + map2.get("temp1")
+ "\t" + map2.get("temp2") + "\t" + map2.get("weather")
+ "\t" + map2.get("ptime"));
} catch (Exception e) {
e.printStackTrace();
}
}
}