Commit 66f352a4 by HlQ

修改查询天气定时任务的执行时间(从每天8点调整到每天5点半)

1 parent 2c49603c
...@@ -14,96 +14,96 @@ import org.springframework.context.annotation.Primary; ...@@ -14,96 +14,96 @@ import org.springframework.context.annotation.Primary;
import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.pool.DruidDataSource;
@Configuration @Configuration
public class DruidDBConfiguration { public class DruidDBConfiguration {
private Logger logger = LoggerFactory.getLogger(DruidDBConfiguration.class); private Logger logger = LoggerFactory.getLogger(DruidDBConfiguration.class);
@Value("${spring.datasource.url:127.0.0.1}") @Value("${spring.datasource.url:127.0.0.1}")
private String dbUrl; private String dbUrl;
@Value("${spring.datasource.username:postgresql}") @Value("${spring.datasource.username:postgresql}")
private String username; private String username;
@Value("${spring.datasource.password:password}") @Value("${spring.datasource.password:password}")
private String password; private String password;
@Value("${spring.datasource.driverClassName:driverClassName}") @Value("${spring.datasource.driverClassName:driverClassName}")
private String driverClassName; private String driverClassName;
@Value("${spring.datasource.initialSize:0}") @Value("${spring.datasource.initialSize:0}")
private int initialSize; private int initialSize;
@Value("${spring.datasource.minIdle:0}") @Value("${spring.datasource.minIdle:0}")
private int minIdle; private int minIdle;
@Value("${spring.datasource.maxActive:1}") @Value("${spring.datasource.maxActive:1}")
private int maxActive; private int maxActive;
@Value("${spring.datasource.maxWait:0}") @Value("${spring.datasource.maxWait:0}")
private int maxWait; private int maxWait;
@Value("${spring.datasource.timeBetweenEvictionRunsMillis:0}") @Value("${spring.datasource.timeBetweenEvictionRunsMillis:0}")
private int timeBetweenEvictionRunsMillis; private int timeBetweenEvictionRunsMillis;
@Value("${spring.datasource.minEvictableIdleTimeMillis:0}") @Value("${spring.datasource.minEvictableIdleTimeMillis:0}")
private int minEvictableIdleTimeMillis; private int minEvictableIdleTimeMillis;
@Value("${spring.datasource.validationQuery:0}") @Value("${spring.datasource.validationQuery:0}")
private String validationQuery; private String validationQuery;
@Value("${spring.datasource.testWhileIdle:false}") @Value("${spring.datasource.testWhileIdle:false}")
private boolean testWhileIdle; private boolean testWhileIdle;
@Value("${spring.datasource.testOnBorrow:false}") @Value("${spring.datasource.testOnBorrow:false}")
private boolean testOnBorrow; private boolean testOnBorrow;
@Value("${spring.datasource.testOnReturn:false}") @Value("${spring.datasource.testOnReturn:false}")
private boolean testOnReturn; private boolean testOnReturn;
@Value("${spring.datasource.poolPreparedStatements:false}") @Value("${spring.datasource.poolPreparedStatements:false}")
private boolean poolPreparedStatements; private boolean poolPreparedStatements;
@Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize:0}") @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize:0}")
private int maxPoolPreparedStatementPerConnectionSize; private int maxPoolPreparedStatementPerConnectionSize;
private String filters; private String filters;
@Value("${spring.datasource.connectionProperties:connectionProperties}") @Value("${spring.datasource.connectionProperties:connectionProperties}")
private String connectionProperties; private String connectionProperties;
@Bean //声明其为Bean实例 @Bean //声明其为Bean实例
@Primary //在同样的DataSource中,首先使用被标注的DataSource @Primary //在同样的DataSource中,首先使用被标注的DataSource
@ConditionalOnExpression("#{'${spring.datasource.driverClassName:false}'!='false'}") @ConditionalOnExpression("#{'${spring.datasource.driverClassName:false}'!='false'}")
public DataSource dataSource(){ public DataSource dataSource() {
DruidDataSource datasource = new DruidDataSource(); DruidDataSource datasource = new DruidDataSource();
if("driverClassName".equals(driverClassName)){ if ("driverClassName".equals(driverClassName)) {
return null; return null;
} }
datasource.setUrl(this.dbUrl); datasource.setUrl(this.dbUrl);
datasource.setUsername(username); datasource.setUsername(username);
datasource.setPassword(password); datasource.setPassword(password);
datasource.setDriverClassName(driverClassName); datasource.setDriverClassName(driverClassName);
//configuration //configuration
datasource.setInitialSize(initialSize); datasource.setInitialSize(initialSize);
datasource.setMinIdle(minIdle); datasource.setMinIdle(minIdle);
datasource.setMaxActive(maxActive); datasource.setMaxActive(maxActive);
datasource.setMaxWait(maxWait); datasource.setMaxWait(maxWait);
datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
datasource.setValidationQuery(validationQuery); datasource.setValidationQuery(validationQuery);
datasource.setTestWhileIdle(testWhileIdle); datasource.setTestWhileIdle(testWhileIdle);
datasource.setTestOnBorrow(testOnBorrow); datasource.setTestOnBorrow(testOnBorrow);
datasource.setTestOnReturn(testOnReturn); datasource.setTestOnReturn(testOnReturn);
datasource.setPoolPreparedStatements(poolPreparedStatements); datasource.setPoolPreparedStatements(poolPreparedStatements);
datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize); datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
try { try {
datasource.setFilters(filters); datasource.setFilters(filters);
} catch (SQLException e) { } catch (SQLException e) {
logger.error("druid configuration initialization filter", e); logger.error("druid configuration initialization filter", e);
} }
datasource.setConnectionProperties(connectionProperties); datasource.setConnectionProperties(connectionProperties);
return datasource; return datasource;
} }
} }
\ No newline at end of file \ No newline at end of file
...@@ -25,77 +25,15 @@ import com.viontech.service.impl.JsonService; ...@@ -25,77 +25,15 @@ import com.viontech.service.impl.JsonService;
* @author zhaibolin * @author zhaibolin
*/ */
@Component @Component
public class SchedulerTask implements CommandLineRunner{ public class SchedulerTask {
@Autowired @Autowired
private JdbcTemplate jdbcTemplate; private WeatherService weatherService;
@Autowired @Scheduled(cron = "0 30 5 * * ? ")
private JsonService jsonService; private void process() throws IOException {
weatherService.getWeatherInfo();
@Autowired
private CityService cityService;
@Autowired
private WeatherService weatherService;
@Scheduled(cron="0 0 8 * * ?")
private void process() throws IOException{
weatherService.getWeatherInfo();
// Date now = new Date();
// LocalDate localDate=now.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
// Date date=java.sql.Date.valueOf(localDate);
// long s=System.currentTimeMillis();
// System.out.println(new Timestamp(s));
// System.out.println(date+"天气服务调用开始");
//// RowMapper<City> rowMapper = new BeanPropertyRowMapper<>(City.class);
//// List<City> Citys = jdbcTemplate.query("select city_id,province_id,weather_code,city_name,province_name from b_city where weather_code is not null and weather_code!='';", rowMapper);
//
//// RowMapper<SimpleWeather> rowMappers = new BeanPropertyRowMapper<>(SimpleWeather.class);
//// List<SimpleWeather> Weathers=jdbcTemplate.query("select province_id,city_id,type,data_date,ltemp,htemp,aqi,wind_intensity from d_weather where data_date='"+date+"';", rowMappers);
//// List<Integer> cityIds = Weathers.stream().map(SimpleWeather::getCity_id).collect(Collectors.toList());
//
// if(cityList.isEmpty()){
// System.out.println("请先给您所在城市添加城市编码");
// }else{
// for (City bcity : cityList) {
// if(cityIds.contains(bcity.getCityId())){
// System.out.println(""+bcity.getProvinceName()+bcity.getCityName()+"天气已经存在");
// continue;
// }
// Integer weatherCode= null;
// try {
// weatherCode = new Integer(bcity.getWeatherCode().trim());
// } catch (NumberFormatException e) {
// continue;
// }
// SimpleWeather simpleWeather= jsonService.getWeatherInfo(weatherCode.intValue());
// if(simpleWeather == null){
// System.out.println(weatherCode.intValue());
// }
//
// jdbcTemplate.update(
// "insert into d_weather(province_id,city_id,type,data_date,ltemp,htemp,aqi,modify_time,create_time,wind_intensity) values(?,?,?,?,?,?,?,NOW(),NOW(),?);",
// bcity.getProvinceId(),
// bcity.getCityId(),
// String.valueOf(simpleWeather.getType()),
// date,
// Integer.parseInt(simpleWeather.getLtemp()),
// Integer.parseInt(simpleWeather.getHtemp()),
// Integer.parseInt(simpleWeather.getAqi()),
// Integer.parseInt(simpleWeather.getFengli().substring(0,1))
// );
// System.out.println(""+bcity.getProvinceName()+bcity.getCityName()+"天气插入成功");
// }
// }
// System.out.println("天气服务调用结束");
} }
//@Override
public void run(String... args) throws Exception {
// TODO Auto-generated method stub
process();
}
} }
\ No newline at end of file \ No newline at end of file
...@@ -20,23 +20,21 @@ import java.util.stream.Collectors; ...@@ -20,23 +20,21 @@ import java.util.stream.Collectors;
public class CityService { public class CityService {
@Autowired @Autowired
private JdbcTemplate jdbcTemplate; private JdbcTemplate jdbcTemplate;
@Autowired @Autowired
private NamedParameterJdbcTemplate namedParameterJdbcTemplate; private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
@Autowired private String SQL_SELECT_MALL = "select name,status,province_id,city_id from b_mall";
private JsonService jsonService; private String SQL_SELECT_CITY = "select area_name as cityName,province_id,weather_code,city_id from b_city where city_id in (:cityIds)";
private String SQL_SELECT_WEATHER = "select city_id from d_weather where data_date=?";
private String SQL_SELECT_MALL="select name,status,province_id,city_id from b_mall";
private String SQL_SELECT_CITY="select area_name as cityName,province_id,weather_code,city_id from b_city where city_id in (:cityIds)";
private String SQL_SELECT_WEATHER="select city_id from d_weather where data_date=?";
public List<Mall> selectMallList(){ public List<Mall> selectMallList() {
List<Mall> mallList= jdbcTemplate.query(SQL_SELECT_MALL,new BeanPropertyRowMapper<>(Mall.class)); List<Mall> mallList = jdbcTemplate.query(SQL_SELECT_MALL, new BeanPropertyRowMapper<>(Mall.class));
return mallList; return mallList;
} }
public List<City> selectCityList(List<Mall> mallList){
if(mallList.isEmpty()){ public List<City> selectCityList(List<Mall> mallList) {
if (mallList.isEmpty()) {
System.out.println("获取不到商场列表"); System.out.println("获取不到商场列表");
return null; return null;
} }
...@@ -46,8 +44,8 @@ public class CityService { ...@@ -46,8 +44,8 @@ public class CityService {
return namedParameterJdbcTemplate.query(SQL_SELECT_CITY, paramMap, new BeanPropertyRowMapper<>(City.class)); return namedParameterJdbcTemplate.query(SQL_SELECT_CITY, paramMap, new BeanPropertyRowMapper<>(City.class));
} }
public List<Integer> selectTodayWeather(Date date){ public List<Integer> selectTodayWeather(Date date) {
List<Integer> cityIdList=jdbcTemplate.queryForList(SQL_SELECT_WEATHER,new Object[]{date},Integer.class); List<Integer> cityIdList = jdbcTemplate.queryForList(SQL_SELECT_WEATHER, new Object[]{date}, Integer.class);
return cityIdList; return cityIdList;
} }
......
...@@ -29,180 +29,179 @@ import org.springframework.web.client.RestTemplate; ...@@ -29,180 +29,179 @@ import org.springframework.web.client.RestTemplate;
@Service @Service
public class JsonService { public class JsonService {
@Resource @Autowired
private JdbcTemplate jdbcTemplate; private Json jsonclass;
@Autowired
private Json jsonclass; public SimpleWeather getWeatherInfo(int cityId) throws IOException {
public SimpleWeather getWeatherInfo(int cityId) throws IOException { String json = getWeatherJson(cityId);
ObjectMapper mapper = new ObjectMapper();
String json = getWeatherJson(cityId); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
ObjectMapper mapper = new ObjectMapper(); mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); WeatherMessage weatherMessage = mapper.readValue(json, WeatherMessage.class);
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
WeatherMessage weatherMessage = mapper.readValue(json, WeatherMessage.class);
// if(!weatherMessage.getCode().equals("0")){ // if(!weatherMessage.getCode().equals("0")){
// throw new RuntimeException(weatherMessage.getMsg()); // throw new RuntimeException(weatherMessage.getMsg());
// } // }
String jsons = getAqiJson(cityId); String jsons = getAqiJson(cityId);
ObjectMapper mappers = new ObjectMapper(); ObjectMapper mappers = new ObjectMapper();
mappers.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mappers.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mappers.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); mappers.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
WeatherMessage weatherMessage2 = mappers.readValue(jsons, WeatherMessage.class); WeatherMessage weatherMessage2 = mappers.readValue(jsons, WeatherMessage.class);
SimpleWeather simpleWeather = weathers2SimpleWeather(weatherMessage,weatherMessage2); SimpleWeather simpleWeather = weathers2SimpleWeather(weatherMessage, weatherMessage2);
return simpleWeather; return simpleWeather;
} }
private String getWeatherJson(int cityId) throws IOException{ private String getWeatherJson(int cityId) throws IOException {
String host = jsonclass.getHost1(); String host = jsonclass.getHost1();
String path = jsonclass.getPath1(); String path = jsonclass.getPath1();
String method = "POST"; String method = "POST";
String appcode = jsonclass.getAppcode(); String appcode = jsonclass.getAppcode();
Map<String, String> headers = new HashMap<String, String>(); Map<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", "APPCODE " + appcode); headers.put("Authorization", "APPCODE " + appcode);
headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
Map<String, String> querys = new HashMap<String, String>(); Map<String, String> querys = new HashMap<String, String>();
Map<String, String> bodys = new HashMap<String, String>(); Map<String, String> bodys = new HashMap<String, String>();
bodys.put("cityId", String.valueOf(cityId)); bodys.put("cityId", String.valueOf(cityId));
HttpResponse response = null; HttpResponse response = null;
try { try {
response = HttpUtils.doPost(host, path, method, headers, querys, bodys); response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
} catch (Exception e) { } catch (Exception e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
// return response.toString(); return EntityUtils.toString(response.getEntity());
return EntityUtils.toString(response.getEntity());
}
}
private String getAqiJson(int cityId) throws IOException{ private String getAqiJson(int cityId) throws IOException {
String host = jsonclass.getHost2(); String host = jsonclass.getHost2();
String path = jsonclass.getPath2(); String path = jsonclass.getPath2();
String method = "POST"; String method = "POST";
String appcode = jsonclass.getAppcode(); String appcode = jsonclass.getAppcode();
Map<String, String> headers = new HashMap<String, String>(); Map<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", "APPCODE " + appcode); headers.put("Authorization", "APPCODE " + appcode);
headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
Map<String, String> querys = new HashMap<String, String>(); Map<String, String> querys = new HashMap<String, String>();
Map<String, String> bodys = new HashMap<String, String>(); Map<String, String> bodys = new HashMap<String, String>();
bodys.put("cityId", String.valueOf(cityId)); bodys.put("cityId", String.valueOf(cityId));
HttpResponse response = null; HttpResponse response = null;
try { try {
response = HttpUtils.doPost(host, path, method, headers, querys, bodys); response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
} catch (Exception e) { } catch (Exception e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
// return response.toString(); // return response.toString();
return EntityUtils.toString(response.getEntity()); return EntityUtils.toString(response.getEntity());
} }
private SimpleWeather weathers2SimpleWeather(WeatherMessage weatherMessage,WeatherMessage weatherMessage2){ private SimpleWeather weathers2SimpleWeather(WeatherMessage weatherMessage, WeatherMessage weatherMessage2) {
Data data = weatherMessage.getData(); Data data = weatherMessage.getData();
if(data == null){ if (data == null) {
return null; return null;
} }
data.getCity(); data.getCity();
data.getForecast(); data.getForecast();
City city = data.getCity(); City city = data.getCity();
if(city == null){ if (city == null) {
return null; return null;
} }
Forecast forecast = data.getForecast().get(0); Forecast forecast = data.getForecast().get(0);
if(forecast == null){ if (forecast == null) {
return null; return null;
} }
SimpleWeather simpleWeather = new SimpleWeather(); SimpleWeather simpleWeather = new SimpleWeather();
simpleWeather.setType(getWeatherCode(forecast.getConditionDay())); simpleWeather.setType(getWeatherCode(forecast.getConditionDay()));
simpleWeather.setData_date(forecast.getPredictDate()); simpleWeather.setData_date(forecast.getPredictDate());
simpleWeather.setHtemp(forecast.getTempDay()); simpleWeather.setHtemp(forecast.getTempDay());
simpleWeather.setLtemp(forecast.getTempNight()); simpleWeather.setLtemp(forecast.getTempNight());
if(weatherMessage2.getData().getAqi()==null){ if (weatherMessage2.getData().getAqi() == null) {
simpleWeather.setAqi("0"); simpleWeather.setAqi("0");
}else{ } else {
simpleWeather.setAqi(weatherMessage2.getData().getAqi().getValue()); simpleWeather.setAqi(weatherMessage2.getData().getAqi().getValue());
} }
simpleWeather.setFengli(forecast.getWindLevelDay()); simpleWeather.setFengli(forecast.getWindLevelDay());
simpleWeather.setFengxiang(forecast.getWindDirDay()); simpleWeather.setFengxiang(forecast.getWindDirDay());
return simpleWeather; return simpleWeather;
} }
private int getWeatherCode(String weather){
switch (weather) { private int getWeatherCode(String weather) {
case "晴": switch (weather) {
case "大部晴朗": case "晴":
return 1; case "大部晴朗":
case "多云": return 1;
case "少云": case "多云":
return 2; case "少云":
case "阴": return 2;
return 3; case "阴":
case "阵雨": return 3;
case "局部阵雨": case "阵雨":
case "小阵雨": case "局部阵雨":
case "强阵雨": case "小阵雨":
return 4; case "强阵雨":
case "雷阵雨": return 4;
case "雷电": case "雷阵雨":
case "雷暴": case "雷电":
return 5; case "雷暴":
case "雷阵雨伴有冰雹": return 5;
case "冰雹": case "雷阵雨伴有冰雹":
case "冰粒": case "冰雹":
case "冰针": case "冰粒":
return 6; case "冰针":
case "雨夹雪": return 6;
return 7; case "雨夹雪":
case "小雨": return 7;
case "小到中雨": case "小雨":
return 8; case "小到中雨":
case "中雨": return 8;
case "雨": case "中雨":
return 9; case "雨":
case "大雨": return 9;
case "中到大雨": case "大雨":
return 10; case "中到大雨":
case "暴雨": return 10;
case "大暴雨": case "暴雨":
case "特大暴雨": case "大暴雨":
case "大到暴雨": case "特大暴雨":
return 11; case "大到暴雨":
case "阵雪": return 11;
case "小阵雪": case "阵雪":
return 12; case "小阵雪":
case "小雪": return 12;
return 13; case "小雪":
case "中雪": return 13;
case "小到中雪": case "中雪":
case "雪": case "小到中雪":
return 14; case "雪":
case "大雪": return 14;
return 15; case "大雪":
case "暴雪": return 15;
return 16; case "暴雪":
case "雾": return 16;
case "冻雾": case "雾":
return 17; case "冻雾":
case "冻雨": return 17;
return 18; case "冻雨":
case "霾": return 18;
case "沙尘暴": case "霾":
case "强沙尘暴": case "沙尘暴":
return 19; case "强沙尘暴":
case "浮尘": return 19;
case "尘卷风": case "浮尘":
case "扬沙": case "尘卷风":
return 20; case "扬沙":
default: return 20;
return -1; default:
} return -1;
} }
}
} }
...@@ -31,21 +31,21 @@ public class WeatherService { ...@@ -31,21 +31,21 @@ public class WeatherService {
public void getWeatherInfo() throws IOException { public void getWeatherInfo() throws IOException {
Date now = new Date(); Date now = new Date();
LocalDate localDate=now.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); LocalDate localDate = now.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
Date date=java.sql.Date.valueOf(localDate); Date date = java.sql.Date.valueOf(localDate);
long s=System.currentTimeMillis(); long s = System.currentTimeMillis();
System.out.println(new Timestamp(s)); System.out.println(new Timestamp(s));
System.out.println(date+"天气服务调用开始"); System.out.println(date + "天气服务调用开始");
List<Mall> mallList=cityService.selectMallList(); List<Mall> mallList = cityService.selectMallList();
List<City> cityList=cityService.selectCityList(mallList); List<City> cityList = cityService.selectCityList(mallList);
List<Integer> cityIds=cityService.selectTodayWeather(date); List<Integer> cityIds = cityService.selectTodayWeather(date);
if(cityList != null) { if (cityList != null) {
for (City bcity : cityList) { for (City bcity : cityList) {
if(cityIds.contains(bcity.getCityId())){ if (cityIds.contains(bcity.getCityId())) {
System.out.println(""+bcity.getCityName()+"天气已经存在"); System.out.println("" + bcity.getCityName() + "天气已经存在");
continue; continue;
} }
Integer weatherCode= null; Integer weatherCode = null;
try { try {
if (bcity.getWeatherCode() == null) { if (bcity.getWeatherCode() == null) {
continue; continue;
...@@ -54,8 +54,8 @@ public class WeatherService { ...@@ -54,8 +54,8 @@ public class WeatherService {
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
continue; continue;
} }
SimpleWeather simpleWeather= jsonService.getWeatherInfo(weatherCode.intValue()); SimpleWeather simpleWeather = jsonService.getWeatherInfo(weatherCode.intValue());
if(simpleWeather == null){ if (simpleWeather == null) {
System.out.println(weatherCode.intValue()); System.out.println(weatherCode.intValue());
} }
...@@ -68,9 +68,9 @@ public class WeatherService { ...@@ -68,9 +68,9 @@ public class WeatherService {
Integer.parseInt(simpleWeather.getLtemp()), Integer.parseInt(simpleWeather.getLtemp()),
Integer.parseInt(simpleWeather.getHtemp()), Integer.parseInt(simpleWeather.getHtemp()),
Integer.parseInt(simpleWeather.getAqi()), Integer.parseInt(simpleWeather.getAqi()),
Integer.parseInt(simpleWeather.getFengli().substring(0,1)) Integer.parseInt(simpleWeather.getFengli().substring(0, 1))
); );
System.out.println(""+bcity.getCityName()+"天气插入成功"); System.out.println("" + bcity.getCityName() + "天气插入成功");
} }
} }
System.out.println("天气服务调用结束"); System.out.println("天气服务调用结束");
......
...@@ -35,281 +35,285 @@ import org.apache.http.message.BasicNameValuePair; ...@@ -35,281 +35,285 @@ import org.apache.http.message.BasicNameValuePair;
* @author zhaibolin * @author zhaibolin
*/ */
public class HttpUtils { public class HttpUtils {
/** /**
* get * get
* *
* @param host * @param host
* @param path * @param path
* @param method * @param method
* @param headers * @param headers
* @param querys * @param querys
* @return * @return
* @throws Exception * @throws Exception
*/ */
public static HttpResponse doGet(String host, String path, String method, public static HttpResponse doGet(String host, String path, String method,
Map<String, String> headers, Map<String, String> headers,
Map<String, String> querys) Map<String, String> querys)
throws Exception { throws Exception {
HttpClient httpClient = wrapClient(host); HttpClient httpClient = wrapClient(host);
HttpGet request = new HttpGet(buildUrl(host, path, querys)); HttpGet request = new HttpGet(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) { for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue()); request.addHeader(e.getKey(), e.getValue());
} }
return httpClient.execute(request); return httpClient.execute(request);
} }
/** /**
* post form * post form
* *
* @param host * @param host
* @param path * @param path
* @param method * @param method
* @param headers * @param headers
* @param querys * @param querys
* @param bodys * @param bodys
* @return * @return
* @throws Exception * @throws Exception
*/ */
public static HttpResponse doPost(String host, String path, String method, public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers, Map<String, String> headers,
Map<String, String> querys, Map<String, String> querys,
Map<String, String> bodys) Map<String, String> bodys)
throws Exception { throws Exception {
HttpClient httpClient = wrapClient(host); HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys)); HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) { for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue()); request.addHeader(e.getKey(), e.getValue());
} }
if (bodys != null) { if (bodys != null) {
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>(); List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
for (String key : bodys.keySet()) { for (String key : bodys.keySet()) {
nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key))); nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
} }
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8"); UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8"); formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
request.setEntity(formEntity); request.setEntity(formEntity);
} }
return httpClient.execute(request); return httpClient.execute(request);
} }
/** /**
* Post String * Post String
* *
* @param host * @param host
* @param path * @param path
* @param method * @param method
* @param headers * @param headers
* @param querys * @param querys
* @param body * @param body
* @return * @return
* @throws Exception * @throws Exception
*/ */
public static HttpResponse doPost(String host, String path, String method, public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers, Map<String, String> headers,
Map<String, String> querys, Map<String, String> querys,
String body) String body)
throws Exception { throws Exception {
HttpClient httpClient = wrapClient(host); HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys)); HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) { for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue()); request.addHeader(e.getKey(), e.getValue());
} }
if (StringUtils.isNotBlank(body)) { if (StringUtils.isNotBlank(body)) {
request.setEntity(new StringEntity(body, "utf-8")); request.setEntity(new StringEntity(body, "utf-8"));
} }
return httpClient.execute(request); return httpClient.execute(request);
} }
/** /**
* Post stream * Post stream
* *
* @param host * @param host
* @param path * @param path
* @param method * @param method
* @param headers * @param headers
* @param querys * @param querys
* @param body * @param body
* @return * @return
* @throws Exception * @throws Exception
*/ */
public static HttpResponse doPost(String host, String path, String method, public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers, Map<String, String> headers,
Map<String, String> querys, Map<String, String> querys,
byte[] body) byte[] body)
throws Exception { throws Exception {
HttpClient httpClient = wrapClient(host); HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys)); HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) { for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue()); request.addHeader(e.getKey(), e.getValue());
} }
if (body != null) { if (body != null) {
request.setEntity(new ByteArrayEntity(body)); request.setEntity(new ByteArrayEntity(body));
} }
return httpClient.execute(request); return httpClient.execute(request);
} }
/** /**
* Put String * Put String
* @param host *
* @param path * @param host
* @param method * @param path
* @param headers * @param method
* @param querys * @param headers
* @param body * @param querys
* @return * @param body
* @throws Exception * @return
*/ * @throws Exception
public static HttpResponse doPut(String host, String path, String method, */
Map<String, String> headers, public static HttpResponse doPut(String host, String path, String method,
Map<String, String> querys, Map<String, String> headers,
String body) Map<String, String> querys,
throws Exception { String body)
HttpClient httpClient = wrapClient(host); throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPut request = new HttpPut(buildUrl(host, path, querys));
HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) { for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue()); request.addHeader(e.getKey(), e.getValue());
} }
if (StringUtils.isNotBlank(body)) { if (StringUtils.isNotBlank(body)) {
request.setEntity(new StringEntity(body, "utf-8")); request.setEntity(new StringEntity(body, "utf-8"));
} }
return httpClient.execute(request); return httpClient.execute(request);
} }
/** /**
* Put stream * Put stream
* @param host *
* @param path * @param host
* @param method * @param path
* @param headers * @param method
* @param querys * @param headers
* @param body * @param querys
* @return * @param body
* @throws Exception * @return
*/ * @throws Exception
public static HttpResponse doPut(String host, String path, String method, */
Map<String, String> headers, public static HttpResponse doPut(String host, String path, String method,
Map<String, String> querys, Map<String, String> headers,
byte[] body) Map<String, String> querys,
throws Exception { byte[] body)
HttpClient httpClient = wrapClient(host); throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPut request = new HttpPut(buildUrl(host, path, querys));
HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) { for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue()); request.addHeader(e.getKey(), e.getValue());
} }
if (body != null) { if (body != null) {
request.setEntity(new ByteArrayEntity(body)); request.setEntity(new ByteArrayEntity(body));
} }
return httpClient.execute(request); return httpClient.execute(request);
} }
/** /**
* Delete * Delete
* *
* @param host * @param host
* @param path * @param path
* @param method * @param method
* @param headers * @param headers
* @param querys * @param querys
* @return * @return
* @throws Exception * @throws Exception
*/ */
public static HttpResponse doDelete(String host, String path, String method, public static HttpResponse doDelete(String host, String path, String method,
Map<String, String> headers, Map<String, String> headers,
Map<String, String> querys) Map<String, String> querys)
throws Exception { throws Exception {
HttpClient httpClient = wrapClient(host); HttpClient httpClient = wrapClient(host);
HttpDelete request = new HttpDelete(buildUrl(host, path, querys)); HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) { for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue()); request.addHeader(e.getKey(), e.getValue());
} }
return httpClient.execute(request); return httpClient.execute(request);
} }
private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException { private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
StringBuilder sbUrl = new StringBuilder(); StringBuilder sbUrl = new StringBuilder();
sbUrl.append(host); sbUrl.append(host);
if (!StringUtils.isBlank(path)) { if (!StringUtils.isBlank(path)) {
sbUrl.append(path); sbUrl.append(path);
} }
if (null != querys) { if (null != querys) {
StringBuilder sbQuery = new StringBuilder(); StringBuilder sbQuery = new StringBuilder();
for (Map.Entry<String, String> query : querys.entrySet()) { for (Map.Entry<String, String> query : querys.entrySet()) {
if (0 < sbQuery.length()) { if (0 < sbQuery.length()) {
sbQuery.append("&"); sbQuery.append("&");
} }
if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) { if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
sbQuery.append(query.getValue()); sbQuery.append(query.getValue());
} }
if (!StringUtils.isBlank(query.getKey())) { if (!StringUtils.isBlank(query.getKey())) {
sbQuery.append(query.getKey()); sbQuery.append(query.getKey());
if (!StringUtils.isBlank(query.getValue())) { if (!StringUtils.isBlank(query.getValue())) {
sbQuery.append("="); sbQuery.append("=");
sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8")); sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
} }
} }
} }
if (0 < sbQuery.length()) { if (0 < sbQuery.length()) {
sbUrl.append("?").append(sbQuery); sbUrl.append("?").append(sbQuery);
} }
} }
return sbUrl.toString(); return sbUrl.toString();
} }
private static HttpClient wrapClient(String host) { private static HttpClient wrapClient(String host) {
HttpClient httpClient = new DefaultHttpClient(); HttpClient httpClient = new DefaultHttpClient();
if (host.startsWith("https://")) { if (host.startsWith("https://")) {
sslClient(httpClient); sslClient(httpClient);
} }
return httpClient; return httpClient;
} }
private static void sslClient(HttpClient httpClient) { private static void sslClient(HttpClient httpClient) {
try { try {
SSLContext ctx = SSLContext.getInstance("TLS"); SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() { X509TrustManager tm = new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() { public X509Certificate[] getAcceptedIssuers() {
return null; return null;
} }
public void checkClientTrusted(X509Certificate[] xcs, String str) { public void checkClientTrusted(X509Certificate[] xcs, String str) {
} }
public void checkServerTrusted(X509Certificate[] xcs, String str) { public void checkServerTrusted(X509Certificate[] xcs, String str) {
} }
}; };
ctx.init(null, new TrustManager[] { tm }, null); ctx.init(null, new TrustManager[]{tm}, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx); SSLSocketFactory ssf = new SSLSocketFactory(ctx);
// ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); // ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = httpClient.getConnectionManager(); ClientConnectionManager ccm = httpClient.getConnectionManager();
SchemeRegistry registry = ccm.getSchemeRegistry(); SchemeRegistry registry = ccm.getSchemeRegistry();
registry.register(new Scheme("https", 443, ssf)); registry.register(new Scheme("https", 443, ssf));
} catch (KeyManagementException ex) { } catch (KeyManagementException ex) {
throw new RuntimeException(ex); throw new RuntimeException(ex);
} catch (NoSuchAlgorithmException ex) { } catch (NoSuchAlgorithmException ex) {
throw new RuntimeException(ex); throw new RuntimeException(ex);
} }
} }
} }
\ No newline at end of file \ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!