获取天气
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.json.JsonObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.platform.sdk.m2.bean.Location;
import com.platform.sdk.m2.bean.WeatherInfo;
import com.platform.sdk.m2.prarm.LauncherAreaWeatherParam;
import com.platform.sdk.m2.util.Code;
import com.platform.web.m2.constants.NumberKeys;
import com.platform.web.m2.constants.ServiceConstants;
import com.platform.web.m2.log.MyLog;
import com.platform.web.m2.util.PlatformConfig;
public class WeatherTest
{
private static String convertStreamToString(InputStream is) {
StringBuilder sb1 = new StringBuilder();
byte[] bytes = new byte[4096];
int size;
try {
while ((size = is.read(bytes)) > 0) {
String str = new String(bytes, 0, size, "UTF-8");
sb1.append(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb1.toString();
}
@Test
public void webServiceApi()
{
String uri = String.format("https://free-api.heweather.com/s6/weather/forecast?location=%s&key=%s", "深圳","c0d7b9f9e3dc4f82845c58673618b2a4");
HttpGet httpGet = new HttpGet(uri);
httpGet.setHeader("Content-Type", "application/json;charset=UTF-8");
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
try
{
response = httpClient.execute(httpGet);
response.setHeader("Content-Type", "application/json;charset=UTF-8");
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK)
{
String result = EntityUtils.toString(response.getEntity());
JSONObject json = JSON.parseObject(result);
System.out.println(json.toString());
return;
}
return;
}
catch (IOException e)
{
MyLog.error("请求第三方接口异常");
return;
}
finally
{
try
{
if (null != response)
{
EntityUtils.consume(response.getEntity());
response.close();
}
httpClient.close();
}
catch (IOException e)
{
MyLog.error("关闭 httpClient 异常");
return;
}
}
}
/**
* 请求新浪获取地址API
* <功能详细描述>
* @param ip ip地址
* @return Location
* @see [类、类#方法、类#成员]
*/
@Test
public void getSinaLocaltion()
{
String uri = String.format("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=%s", "120.79.184.201");
HttpGet httpGet = new HttpGet(uri);
httpGet.setHeader("Content-Type", "application/json;charset=UTF-8");
CloseableHttpClient httpClient = HttpClients.createDefault();
//RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).build();
//httpGet.setConfig(requestConfig);
CloseableHttpResponse response = null;
try
{
response = httpClient.execute(httpGet);
response.setHeader("Content-Type", "application/json;charset=UTF-8");
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK)
{
String result = EntityUtils.toString(response.getEntity());
JSONObject json = JSON.parseObject(result);
if (null == json)
{
return;
}
Integer ret = Integer.parseInt(String.valueOf(json.get("ret")));
if (ret != NumberKeys.NUM_1)
{
return;
}
String province = String.valueOf(json.get("province"));
String city = String.valueOf(json.get("city"));
Location location = new Location();
location.setProvinceName(province);
location.setCityName(city);
return;
}
return;
}
catch (IOException e)
{
return;
}
finally
{
try
{
if (null != response)
{
EntityUtils.consume(response.getEntity());
response.close();
}
httpClient.close();
}
catch (IOException e)
{
MyLog.error("释放资源异常");
}
}
}
@Test
public void getAreaWeather() throws ClientProtocolException, IOException
{
// 前端可以传ip或者城市名 都可以查下到相对应的天气
// 前端5小时调用一次后台获取天气 我是本地缓存城市天气 如果相隔四个小时就会根据api获取天气
//出于第三方服务器压力考虑
String city = "深圳";
String cityName = null;
String provinceName = null;
String ip = "120.236.15.10";
// 获取地区
Location location = getArea(ip);
// 城市名称
provinceName = location.getProvinceName();
cityName = location.getCityName();
MyLog.debug("provinceName : {} city:{}", provinceName, cityName);
MyLog.debug("location:{}", JSONObject.toJSONString(location));
// 获取中华万年历天气
WeatherInfo weather = getChinaCalendarWeather(city);
MyLog.debug("wannianli get weather",weather);
if (null == weather)
{
// 获取中国天气
weather = getChinaWeather(city);
}
MyLog.debug("zhongguo get weather",weather);
if (null == weather)
{
// 获取和风天气
weather = getHeWeather(city);
}
MyLog.debug("hefeng get weather",weather);
if (null == weather)
{
MyLog.error("无法获取{}天气", city);
MyLog.debug("get {} weather error",city);
}else{
System.out.println(JSONObject.toJSONString(weather));
}
}
/**
* 中华万年历天气
* <功能详细描述>
* @param city
* @return
* @throws IOException
* @throws ClientProtocolException
* @see [类、类#方法、类#成员]
*/
public WeatherInfo getChinaCalendarWeather(String city) throws ClientProtocolException, IOException
{
MyLog.info("调用中华万年历天气接口");
WeatherInfo weather = null;
CloseableHttpClient client;
client = HttpClients.createDefault();
HttpGet get = new HttpGet("http://wthrcdn.etouch.cn/weather_mini?city=" + city);
HttpResponse response;
JSONObject json = null;
response = client.execute(get);
HttpEntity entity = response.getEntity();
if (entity != null)
{
InputStream instreams = entity.getContent();
String str = convertStreamToString(instreams);
get.abort();
json = JSONObject.parseObject(str);
MyLog.info(json.toString());
// 城市名称错误 获取不到城市天气
if (NumberKeys.NUM_1000 != Integer.parseInt(json.get("status").toString()))
{
MyLog.error("获取不到城市的天气状况", city);
return null;
}
}
JSONObject data = JSONObject.parseObject(String.valueOf(json.get("data")));
if (null == data)
{
MyLog.error("获取不到城市的天气状况", city);
return null;
}
String wendu = String.valueOf(data.get("wendu"));
JSONArray forecast = JSONArray.parseArray(String.valueOf(data.get("forecast")));
JSONObject forecastJson = JSONObject.parseObject(forecast.get(0).toString());
String fengli = String.valueOf(forecastJson.get("fengli")).substring(9,
String.valueOf(forecastJson.get("fengli")).length() - 3);
String fengxiang = String.valueOf(forecastJson.get("fengxiang"));
String type = String.valueOf(forecastJson.get("type"));
String lowTemp = String.valueOf(forecastJson.get("low")).substring(3);
String highTemp = String.valueOf(forecastJson.get("high")).substring(3);
weather = new WeatherInfo();
weather.setTemp(wendu);
weather.setWindPower(fengli);
weather.setWindDirection(fengxiang);
weather.setWeather(type);
weather.setLowTemp(lowTemp);
weather.setHighTemp(highTemp);
return weather;
}
/**
* 获取中国天气
* <功能详细描述>
* @param cityName 城市名称
* @return WeatherInfo 天气数据
* @throws UnsupportedEncodingException
* @see [类、类#方法、类#成员]
*/
private WeatherInfo getChinaWeather(String cityName) throws UnsupportedEncodingException
{
String cityCode = getCityCode(cityName);
String uri = String.format("http://d1.weather.com.cn/sk_2d/%s.html?_=%s", cityCode, System.currentTimeMillis());
HttpGet httpGet = new HttpGet(uri);
//httpGet.setHeader("Content-Type", "application/json;charset=UTF-8");
httpGet.setHeader("User-Agent",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36");
httpGet.setHeader("Referer", "http://www.weather.com.cn/weather1d/" + cityCode + ".shtml");
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
CloseableHttpResponse response2 = null;
try
{
response = httpClient.execute(httpGet);
//response.setHeader("Content-Type", "application/json;charset=UTF-8");
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK)
{
String result = EntityUtils.toString(response.getEntity(), "utf-8");
try
{
JSONObject json = JSON.parseObject(result.split("=")[1]);
if (null == json)
{
return null;
}
// 温度
String temp = json.getString("temp");
// 风向
String wd = json.getString("WD");
// 风等级
String ws = json.getString("WS");
// 天气状况
String weather = json.getString("weather");
uri = String.format("http://d1.weather.com.cn/dingzhi/%s.html?_=%s",
cityCode,
System.currentTimeMillis());
httpGet = new HttpGet(uri);
//httpGet.setHeader("Content-Type", "application/json;charset=UTF-8");
httpGet.setHeader("User-Agent",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36");
httpGet.setHeader("Referer", "http://www.weather.com.cn/weather1d/" + cityCode + ".shtml");
response2 = httpClient.execute(httpGet);
//response2.setHeader("Content-Type", "application/json;charset=UTF-8");
statusCode = response2.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK)
{
result = EntityUtils.toString(response2.getEntity(), "utf-8");
String cityWeather = result.split(";")[0].toString();
if (!StringUtils.isEmpty(cityWeather))
{
String weatherInfo = cityWeather.split("=")[1].toString();
if (!StringUtils.isEmpty(weatherInfo))
{
JSONObject hisWeather =
JSON.parseObject(JSON.parseObject(weatherInfo).getString("weatherinfo"));
// 最低温度
String lowTemp = hisWeather.getString("tempn");
// 最高温度
String highTemp = hisWeather.getString("temp");
WeatherInfo areaWeather = new WeatherInfo();
areaWeather.setHighTemp(highTemp);
areaWeather.setLowTemp(lowTemp);
areaWeather.setWindDirection(wd);
areaWeather.setWindPower(ws);
areaWeather.setTemp(temp);
areaWeather.setWeather(weather);
return areaWeather;
}
}
}
}
catch (Exception e)
{
MyLog.error("无法获取城市的天气{}", cityName);
return null;
}
}
}
catch (IOException e)
{
MyLog.error("请求第三方接口异常");
return null;
}
finally
{
try
{
if (null != response)
{
EntityUtils.consume(response.getEntity());
response.close();
}
if (null != response2)
{
EntityUtils.consume(response2.getEntity());
response2.close();
}
httpClient.close();
}
catch (IOException e)
{
MyLog.error("关闭 httpClient 异常");
return null;
}
}
return null;
}
/**
* 中国天气接口
* <功能详细描述>
* @param city
* @return
* @throws UnsupportedEncodingException
* @see [类、类#方法、类#成员]
*/
public String getCityCode(String city) throws UnsupportedEncodingException
{
// 先从数据库中获取城市编码,不存在则新增
String dbCityCode = null;
if (null != dbCityCode)
{
return dbCityCode;
}
MyLog.info("调用中国天气网查询城市编码接口");
BufferedReader bufferedReader = null;
InputStreamReader inputStreamReader = null;
InputStream inputStream = null;
HttpURLConnection httpUrlConn = null;
String cityCode = ServiceConstants.BEIJING_CITY_CODE;
// 获取城市编码
String uri = String.format("http://toy1.weather.com.cn/search?cityname=%s", URLEncoder.encode(city, "utf-8"));
// 建立get请求
URL url;
try
{
url = new URL(uri);
httpUrlConn = (HttpURLConnection)url.openConnection();
httpUrlConn.setDoInput(true);
httpUrlConn.setReadTimeout(3000);
httpUrlConn.setConnectTimeout(3000);
httpUrlConn.setRequestMethod("GET");
// 获取输入流
inputStream = httpUrlConn.getInputStream();
inputStreamReader = new InputStreamReader(inputStream, "utf-8");
bufferedReader = new BufferedReader(inputStreamReader);
// 从输入流读取结果
StringBuffer buffer = new StringBuffer();
String str = null;
while ((str = bufferedReader.readLine()) != null)
{
buffer.append(str);
}
MyLog.info(buffer.toString());
String codeStr = buffer.toString().substring(1, buffer.toString().length() - 1);
JSONArray array = JSON.parseArray(codeStr);
if (NumberKeys.NUM_0 == array.size())
{
MyLog.error("中国天气网获取城市编码异常...");
}
else
{
JSONObject cityInfo = JSON.parseObject(array.get(0).toString());
cityCode = cityInfo.get("ref").toString().substring(0, 9);
// launcherMapper.insertCityCode(cityCode, city);
}
}
catch (Exception e)
{
MyLog.error("获取万年历天气异常...");
}
finally
{
// 释放资源
try
{
if (null != bufferedReader)
{
bufferedReader.close();
}
if (null != inputStreamReader)
{
inputStreamReader.close();
}
if (null != inputStream)
{
inputStream.close();
}
if (null != httpUrlConn)
{
httpUrlConn.disconnect();
}
}
catch (IOException e)
{
System.out.println("释放资源异常...");
}
}
return cityCode;
}
/**
* 和风天气 (免费用户只允许1000次调用)
* <功能详细描述>
* @param cityName
* @return
* @see [类、类#方法、类#成员]
*/
private WeatherInfo getHeWeather(String cityName)
{
// 获取和风天气
String hefengKey = "c0d7b9f9e3dc4f82845c58......";
String uri =
String.format("https://free-api.heweather.com/s6/weather/now?location=%s&key=%s", cityName, hefengKey);
JSONObject heWeather6Now = webServiceApi(uri);
if (null == heWeather6Now)
{
return null;
}
JSONArray heWeather6ArrayNow = JSON.parseArray(heWeather6Now.getString("HeWeather6"));
if (null == heWeather6ArrayNow || heWeather6ArrayNow.size() == 0)
{
return null;
}
JSONObject weatherJson = JSONObject.parseObject(heWeather6ArrayNow.get(0).toString());
if (!"ok".equals(weatherJson.getString("status")))
{
return null;
}
uri =
String.format("https://free-api.heweather.com/s6/weather/forecast?location=%s&key=%s", cityName, hefengKey);
JSONObject HeWeather6 = webServiceApi(uri);
if (null == HeWeather6)
{
return null;
}
JSONArray heWeather6Array = JSON.parseArray(HeWeather6.getString("HeWeather6"));
if (null == heWeather6Array || heWeather6Array.size() == 0)
{
return null;
}
JSONObject weatherJson2 = JSONObject.parseObject(heWeather6Array.get(0).toString());
if (!"ok".equals(weatherJson2.getString("status")))
{
return null;
}
// 天气实况
JSONObject dailyForecastNow = JSONObject.parseObject(weatherJson.getString("now"));
// 预报天气
JSONArray dailyForecastArray = JSONObject.parseArray(weatherJson2.getString("daily_forecast"));
if (null == dailyForecastNow || null == dailyForecastArray || NumberKeys.NUM_0 == dailyForecastArray.size())
{
return null;
}
JSONObject dailyForecast = JSONObject.parseObject(dailyForecastArray.get(0).toString());
if (null == dailyForecast)
{
return null;
}
WeatherInfo weather = new WeatherInfo();
weather.setWeather(dailyForecastNow.getString("cond_txt"));
weather.setWindDirection(dailyForecastNow.getString("wind_dir"));
weather.setWindPower(dailyForecastNow.getString("wind_sc"));
weather.setTemp(dailyForecastNow.getString("tmp"));
weather.setLowTemp(dailyForecast.getString("tmp_min"));
weather.setHighTemp(dailyForecast.getString("tmp_max"));
return weather;
}
public JSONObject webServiceApi(String uri)
{
MyLog.info("请求api:" + uri);
HttpGet httpGet = new HttpGet(uri);
httpGet.setHeader("Content-Type", "application/json;charset=UTF-8");
CloseableHttpClient httpClient = HttpClients.createDefault();
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();
httpGet.setConfig(requestConfig);
CloseableHttpResponse response = null;
try
{
response = httpClient.execute(httpGet);
response.setHeader("Content-Type", "application/json;charset=UTF-8");
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK)
{
String result = EntityUtils.toString(response.getEntity(), "utf-8");
JSONObject json = JSON.parseObject(result);
return json;
}
return null;
}
catch (IOException e)
{
MyLog.error("请求第三方接口异常");
return null;
}
finally
{
try
{
if (null != response)
{
EntityUtils.consume(response.getEntity());
response.close();
}
httpClient.close();
}
catch (IOException e)
{
MyLog.error("关闭 httpClient 异常");
return null;
}
}
}
/**
* 获取地区
* <功能详细描述>
* @param ip
* @return
* @see [类、类#方法、类#成员]
*/
private Location getArea(String ip)
{
String province = null;
String city = null;
JSONObject json = null;
String uri = null;
// 获取新浪地址
Location location = getTaobaoLocaltion(ip);
/*if (!checkLocation(location))
{
// 获取淘宝地址
location = getSinaLocaltion(ip);
}*/
if (!checkLocation(location))
{
MyLog.error("淘宝地址获取失败");
MyLog.info("获取百度地址");
// 获取百度位置
String baiduAk = "Z2jjwUHuNOVrQXGVMg.....";
uri = String.format("http://api.map.baidu.com/location/ip?ak=%s&ip=%s", baiduAk, ip);
json = webServiceApi(uri);
if (null == json || Code.SUCCESS != Integer.parseInt(json.get("status").toString()))
{
MyLog.error("百度地址获取失败");
}
else
{
JSONObject content = JSONObject.parseObject(String.valueOf(json.get("content")));
JSONObject addressDetail = JSONObject.parseObject(String.valueOf(content.get("address_detail")));
province = String.valueOf(addressDetail.get("province"));
city = String.valueOf(addressDetail.get("city"));
location = new Location();
location.setProvinceName(province);
location.setCityName(city);
}
}
if (!checkLocation(location))
{
// 获取腾讯位置
MyLog.info("获取腾讯地址");
String tengxunKey = "7YMBZ-JGJL6-63DSR-ELFTG......";
uri = String.format("https://apis.map.qq.com/ws/location/v1/ip?ip=%s&key=%s", ip, tengxunKey);
json = webServiceApi(uri);
if (null == json || Code.SUCCESS != Integer.parseInt(String.valueOf(json.get("status"))))
{
MyLog.error("腾讯地址获取失败");
}
else
{
JSONObject result = JSONObject.parseObject(String.valueOf(json.get("result")));
JSONObject addressDetail = JSONObject.parseObject(String.valueOf(result.get("ad_info")));
province = String.valueOf(addressDetail.get("province"));
city = String.valueOf(addressDetail.get("city"));
location = new Location();
location.setProvinceName(province);
location.setCityName(city);
}
}
if (!checkLocation(location))
{
location = new Location();
location.setProvinceName("北京市");
location.setCityName("北京");
}
return location;
}
/**
* 校验位置
* <功能详细描述>
* @param location 位置
* @return boolean 校验是否通过
* @see [类、类#方法、类#成员]
*/
private boolean checkLocation(Location location)
{
if (null == location || StringUtils.isEmpty(location.getProvinceName())
|| StringUtils.isEmpty(location.getCityName()))
{
return false;
}
return true;
}
/**
* 请求淘宝获取地址API
* <功能详细描述>
* @param ip ip地址
* @return Location
* @see [类、类#方法、类#成员]
*/
private Location getTaobaoLocaltion(String ip)
{
BufferedReader bufferedReader = null;
InputStreamReader inputStreamReader = null;
InputStream inputStream = null;
HttpURLConnection httpUrlConn = null;
try
{
String uri = String.format("http://ip.taobao.com/service/getIpInfo.php?ip=%s", ip);
// 建立get请求
URL url = new URL(uri);
httpUrlConn = (HttpURLConnection)url.openConnection();
httpUrlConn.setDoInput(true);
httpUrlConn.setRequestMethod("GET");
httpUrlConn.setReadTimeout(3000);
httpUrlConn.setConnectTimeout(3000);
// 获取输入流
inputStream = httpUrlConn.getInputStream();
inputStreamReader = new InputStreamReader(inputStream, "utf-8");
bufferedReader = new BufferedReader(inputStreamReader);
// 从输入流读取结果
StringBuffer buffer = new StringBuffer();
String str = null;
while ((str = bufferedReader.readLine()) != null)
{
buffer.append(str);
}
JSONObject json = JSON.parseObject(buffer.toString());
if (null == json)
{
return null;
}
Integer code = Integer.parseInt(String.valueOf(json.get("code")));
if (code != NumberKeys.NUM_0)
{
return null;
}
JSONObject data = json.getJSONObject("data");
String province = String.valueOf(data.get("region"));
String city = String.valueOf(data.get("city"));
// 省份和城市都有数据
if (!StringUtils.isEmpty(province) && !StringUtils.isEmpty(city) && !"XX".equals(province)
&& !"XX".equals(city))
{
Location location = new Location();
location.setProvinceName(province);
location.setCityName(city);
return location;
}
}
catch (Exception e)
{
MyLog.error("获取淘宝位置异常");
}
finally
{
// 释放资源
try
{
if (null != bufferedReader)
{
bufferedReader.close();
}
if (null != inputStreamReader)
{
inputStreamReader.close();
}
if (null != inputStream)
{
inputStream.close();
}
if (null != httpUrlConn)
{
httpUrlConn.disconnect();
}
}
catch (IOException e)
{
MyLog.error("释放资源异常");
}
}
return null;
}
}