Commit 66f352a4 by HlQ

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

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