From bed348df8da724bdb14f844bf8c7b2508b108776 Mon Sep 17 00:00:00 2001 From: wd <1162334221@qq.com> Date: Sat, 7 May 2022 09:50:43 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A4=A9=E6=B0=94=E6=8E=A5=E5=8F=A3=E5=8F=8A?= =?UTF-8?q?=E9=80=86=E5=9C=B0=E7=90=86=E7=BC=96=E7=A0=81=E5=B7=A5=E5=85=B7?= =?UTF-8?q?=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../xkrs/controller/GaodeApiController.java | 79 +++ .../com/xkrs/model/vo/GaoDeIgGeocodeVo.java | 643 ++++++++++++++++++ .../com/xkrs/model/vo/GaoDeWeatherVo.java | 296 ++++++++ .../java/com/xkrs/utils/CommonConstant.java | 11 +- .../java/com/xkrs/utils/GaoDeApiUtil.java | 58 ++ .../java/com/xkrs/utils/HttpClientUtils.java | 193 ++++++ 6 files changed, 1279 insertions(+), 1 deletion(-) create mode 100644 src/main/java/com/xkrs/controller/GaodeApiController.java create mode 100644 src/main/java/com/xkrs/model/vo/GaoDeIgGeocodeVo.java create mode 100644 src/main/java/com/xkrs/model/vo/GaoDeWeatherVo.java create mode 100644 src/main/java/com/xkrs/utils/GaoDeApiUtil.java create mode 100644 src/main/java/com/xkrs/utils/HttpClientUtils.java diff --git a/src/main/java/com/xkrs/controller/GaodeApiController.java b/src/main/java/com/xkrs/controller/GaodeApiController.java new file mode 100644 index 0000000..bc24e95 --- /dev/null +++ b/src/main/java/com/xkrs/controller/GaodeApiController.java @@ -0,0 +1,79 @@ +package com.xkrs.controller; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; +import com.xkrs.common.encapsulation.PromptMessageEnum; +import com.xkrs.model.vo.GaoDeIgGeocodeVo; +import com.xkrs.model.vo.GaoDeWeatherVo; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.i18n.LocaleContextHolder; +import org.springframework.web.bind.annotation.*; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Locale; + +import static com.xkrs.common.encapsulation.OutputEncapsulation.outputEncapsulationObject; +import static com.xkrs.utils.CommonConstant.*; +import static com.xkrs.utils.HttpClientUtils.sendHttpsGet; + +/** + * @author wudong + * @date 2022/5/6 16:13 + * @description 高德api接口 + */ +@RestController +@RequestMapping(value = "/gaode") +public class GaodeApiController { + private static final Logger log = LoggerFactory.getLogger(GaodeApiController.class); + Locale locale = LocaleContextHolder.getLocale(); + + @RequestMapping(value = "/weather", method = RequestMethod.GET) + public String weather(@RequestParam("code") String code) { + if (code.length() < 6) { + return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"编码格式错误", locale); + } + if (code.length() > 6) { + code = code.substring(0, 6); + } + String url = WEATHER_URL + "?key=" + WEATHER_KEY + "&extensions=all&city=" + code; + try { + String res = sendHttpsGet(url); + GaoDeWeatherVo gaoDeWeatherVo = JSON.parseObject(res, new TypeReference<>(){}); + return outputEncapsulationObject(PromptMessageEnum.SUCCESS, gaoDeWeatherVo, locale); + } catch (Exception e) { + log.error("获取高德天气失败, {}", e.getMessage()); + } + return outputEncapsulationObject(PromptMessageEnum.PROCESS_FAIL, "获取高德天气失败", locale); + } + + /** + * 逆地理编码 + * @param location + * @return + */ + @RequestMapping(value = "/ig", method = RequestMethod.POST) + public String geocode(@RequestBody List location) { + if (location.size() == 0) { + return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"格式错误", locale); + } + StringBuilder sb = new StringBuilder(); + for (String var : + location) { + sb.append(var).append("|"); + } + String url = INVERSEGEOGRAPHY_URL + "?key=" + INVERSEGEOGRAPHY_KEY + "&radius=1000&extensions=all&batch=true&roadlevel=0&location="; + try { + String encode = URLEncoder.encode(sb.toString(), StandardCharsets.UTF_8); + String res = sendHttpsGet(url + encode); + GaoDeIgGeocodeVo gaoDeIgGeocodeVo = JSON.parseObject(res, GaoDeIgGeocodeVo.class); + return outputEncapsulationObject(PromptMessageEnum.SUCCESS, gaoDeIgGeocodeVo, locale); + } catch (Exception e) { + log.error("获取高德天气失败, {}", e.getMessage()); + } + return outputEncapsulationObject(PromptMessageEnum.PROCESS_FAIL, "获取高德天气失败", locale); + } + +} diff --git a/src/main/java/com/xkrs/model/vo/GaoDeIgGeocodeVo.java b/src/main/java/com/xkrs/model/vo/GaoDeIgGeocodeVo.java new file mode 100644 index 0000000..f7a6ac9 --- /dev/null +++ b/src/main/java/com/xkrs/model/vo/GaoDeIgGeocodeVo.java @@ -0,0 +1,643 @@ +package com.xkrs.model.vo; + +import java.util.List; + +/** + * @author wudong + * @date 2022/5/6 17:38 + * @description + */ +public class GaoDeIgGeocodeVo { + + private String status; + private String info; + private String infocode; + private List regeocodes; + + public GaoDeIgGeocodeVo() { + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getInfo() { + return info; + } + + public void setInfo(String info) { + this.info = info; + } + + public String getInfocode() { + return infocode; + } + + public void setInfocode(String infocode) { + this.infocode = infocode; + } + + public List getRegeocodes() { + return regeocodes; + } + + public void setRegeocodes(List regeocodes) { + this.regeocodes = regeocodes; + } +} + +class Regeocode { + private String formatted_address; + private List addressComponent; + private List pois; + private List roads; + private List roadinters; + private List aois; + + + public Regeocode() { + } + + public String getFormatted_address() { + return formatted_address; + } + + public void setFormatted_address(String formatted_address) { + this.formatted_address = formatted_address; + } + + public List getAddressComponent() { + return addressComponent; + } + + public void setAddressComponent(List addressComponent) { + this.addressComponent = addressComponent; + } + + public List getPois() { + return pois; + } + + public void setPois(List pois) { + this.pois = pois; + } + + public List getRoads() { + return roads; + } + + public void setRoads(List roads) { + this.roads = roads; + } + + public List getRoadinters() { + return roadinters; + } + + public void setRoadinters(List roadinters) { + this.roadinters = roadinters; + } + + public List getAois() { + return aois; + } + + public void setAois(List aois) { + this.aois = aois; + } +} + +class AddressComponent { + private String country; + private String province; + private String city; + private String citycode; + private String district; + private String adcode; + private String township; + private String towncode; + private String seaArea; + private Neighborhood neighborhood; + private Building building; + private StreetNumber streetNumber; + private List businessAreas; + + public AddressComponent() { + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + public String getProvince() { + return province; + } + + public void setProvince(String province) { + this.province = province; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getCitycode() { + return citycode; + } + + public void setCitycode(String citycode) { + this.citycode = citycode; + } + + public String getDistrict() { + return district; + } + + public void setDistrict(String district) { + this.district = district; + } + + public String getAdcode() { + return adcode; + } + + public void setAdcode(String adcode) { + this.adcode = adcode; + } + + public String getTownship() { + return township; + } + + public void setTownship(String township) { + this.township = township; + } + + public String getTowncode() { + return towncode; + } + + public void setTowncode(String towncode) { + this.towncode = towncode; + } + + public String getSeaArea() { + return seaArea; + } + + public void setSeaArea(String seaArea) { + this.seaArea = seaArea; + } + + public Neighborhood getNeighborhood() { + return neighborhood; + } + + public void setNeighborhood(Neighborhood neighborhood) { + this.neighborhood = neighborhood; + } + + public Building getBuilding() { + return building; + } + + public void setBuilding(Building building) { + this.building = building; + } + + public StreetNumber getStreetNumber() { + return streetNumber; + } + + public void setStreetNumber(StreetNumber streetNumber) { + this.streetNumber = streetNumber; + } + + public List getBusinessAreas() { + return businessAreas; + } + + public void setBusinessAreas(List businessAreas) { + this.businessAreas = businessAreas; + } +} + +class Neighborhood { + private String name; + private String type; + + public Neighborhood() { + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } +} + +class Building { + private String name; + private String type; + + public Building() { + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } +} + +class StreetNumber { + private String street; + private String number; + private String location; + private String direction; + private String distance; + + public StreetNumber() { + } + + public String getStreet() { + return street; + } + + public void setStreet(String street) { + this.street = street; + } + + public String getNumber() { + return number; + } + + public void setNumber(String number) { + this.number = number; + } + + public String getLocation() { + return location; + } + + public void setLocation(String location) { + this.location = location; + } + + public String getDirection() { + return direction; + } + + public void setDirection(String direction) { + this.direction = direction; + } + + public String getDistance() { + return distance; + } + + public void setDistance(String distance) { + this.distance = distance; + } +} + +class BusinessArea { + private String businessArea; + private String location; + private String name; + private String id; + + public BusinessArea() { + } + + public String getBusinessArea() { + return businessArea; + } + + public void setBusinessArea(String businessArea) { + this.businessArea = businessArea; + } + + public String getLocation() { + return location; + } + + public void setLocation(String location) { + this.location = location; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } +} + +class Road { + private String id; + private String name; + private String distance; + private String direction; + private String location; + + public Road() { + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDistance() { + return distance; + } + + public void setDistance(String distance) { + this.distance = distance; + } + + public String getDirection() { + return direction; + } + + public void setDirection(String direction) { + this.direction = direction; + } + + public String getLocation() { + return location; + } + + public void setLocation(String location) { + this.location = location; + } +} + +class Roadinter { + private String distance; + private String direction; + private String location; + private String first_id; + private String first_name; + private String second_id; + private String second_name; + + public Roadinter() { + } + + public String getDistance() { + return distance; + } + + public void setDistance(String distance) { + this.distance = distance; + } + + public String getDirection() { + return direction; + } + + public void setDirection(String direction) { + this.direction = direction; + } + + public String getLocation() { + return location; + } + + public void setLocation(String location) { + this.location = location; + } + + public String getFirst_id() { + return first_id; + } + + public void setFirst_id(String first_id) { + this.first_id = first_id; + } + + public String getFirst_name() { + return first_name; + } + + public void setFirst_name(String first_name) { + this.first_name = first_name; + } + + public String getSecond_id() { + return second_id; + } + + public void setSecond_id(String second_id) { + this.second_id = second_id; + } + + public String getSecond_name() { + return second_name; + } + + public void setSecond_name(String second_name) { + this.second_name = second_name; + } +} + +class Poi { + private String id; + private String name; + private String type; + private String tel; + private String distance; + private String direction; + private String address; + private String location; + private String businessarea; + + public Poi() { + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getTel() { + return tel; + } + + public void setTel(String tel) { + this.tel = tel; + } + + public String getDistance() { + return distance; + } + + public void setDistance(String distance) { + this.distance = distance; + } + + public String getDirection() { + return direction; + } + + public void setDirection(String direction) { + this.direction = direction; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public String getLocation() { + return location; + } + + public void setLocation(String location) { + this.location = location; + } + + public String getBusinessarea() { + return businessarea; + } + + public void setBusinessarea(String businessarea) { + this.businessarea = businessarea; + } +} + +class Aoi { + private String id; + private String name; + private String adcode; + private String location; + private String area; + private String distance; + + public Aoi() { + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getAdcode() { + return adcode; + } + + public void setAdcode(String adcode) { + this.adcode = adcode; + } + + public String getLocation() { + return location; + } + + public void setLocation(String location) { + this.location = location; + } + + public String getArea() { + return area; + } + + public void setArea(String area) { + this.area = area; + } + + public String getDistance() { + return distance; + } + + public void setDistance(String distance) { + this.distance = distance; + } +} diff --git a/src/main/java/com/xkrs/model/vo/GaoDeWeatherVo.java b/src/main/java/com/xkrs/model/vo/GaoDeWeatherVo.java new file mode 100644 index 0000000..fa37353 --- /dev/null +++ b/src/main/java/com/xkrs/model/vo/GaoDeWeatherVo.java @@ -0,0 +1,296 @@ +package com.xkrs.model.vo; + +import java.util.List; + +/** + * @author wudong + * @date 2022/5/6 16:42 + * @description 高德天气接受类 + */ +public class GaoDeWeatherVo { + + private String status; + private String count; + private String info; + private String infocode; +// private Live lives; + private List forecasts; + + public GaoDeWeatherVo() { + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getCount() { + return count; + } + + public void setCount(String count) { + this.count = count; + } + + public String getInfo() { + return info; + } + + public void setInfo(String info) { + this.info = info; + } + + public String getInfocode() { + return infocode; + } + + public void setInfocode(String infocode) { + this.infocode = infocode; + } + + + public List getForecasts() { + return forecasts; + } + + public void setForecasts(List forecasts) { + this.forecasts = forecasts; + } +} + +class Live { + private String province; + private String city; + private String adcode; + private String weather; + private String temperature; + private String winddirection; + private String windpower; + private String humidity; + private String reporttime; + + public Live() { + } + + public String getProvince() { + return province; + } + + public void setProvince(String province) { + this.province = province; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getAdcode() { + return adcode; + } + + public void setAdcode(String adcode) { + this.adcode = adcode; + } + + public String getWeather() { + return weather; + } + + public void setWeather(String weather) { + this.weather = weather; + } + + public String getTemperature() { + return temperature; + } + + public void setTemperature(String temperature) { + this.temperature = temperature; + } + + public String getWinddirection() { + return winddirection; + } + + public void setWinddirection(String winddirection) { + this.winddirection = winddirection; + } + + public String getWindpower() { + return windpower; + } + + public void setWindpower(String windpower) { + this.windpower = windpower; + } + + public String getHumidity() { + return humidity; + } + + public void setHumidity(String humidity) { + this.humidity = humidity; + } + + public String getReporttime() { + return reporttime; + } + + public void setReporttime(String reporttime) { + this.reporttime = reporttime; + } +} + +class Forecast { + private String city; + private String adcode; + private String province; + private String reporttime; + private List casts; + + public Forecast() { + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getAdcode() { + return adcode; + } + + public void setAdcode(String adcode) { + this.adcode = adcode; + } + + public String getProvince() { + return province; + } + + public void setProvince(String province) { + this.province = province; + } + + public String getReporttime() { + return reporttime; + } + + public void setReporttime(String reporttime) { + this.reporttime = reporttime; + } + + public List getCasts() { + return casts; + } + + public void setCasts(List casts) { + this.casts = casts; + } +} + +class Cast { + private String date; + private String week; + private String dayweather; + private String nightweather; + private String daytemp; + private String nighttemp; + private String daywind; + private String nightwind ; + private String daypower ; + private String nightpower ; + + public Cast() { + } + + public String getDate() { + return date; + } + + public void setDate(String date) { + this.date = date; + } + + public String getWeek() { + return week; + } + + public void setWeek(String week) { + this.week = week; + } + + public String getDayweather() { + return dayweather; + } + + public void setDayweather(String dayweather) { + this.dayweather = dayweather; + } + + public String getNightweather() { + return nightweather; + } + + public void setNightweather(String nightweather) { + this.nightweather = nightweather; + } + + public String getDaytemp() { + return daytemp; + } + + public void setDaytemp(String daytemp) { + this.daytemp = daytemp; + } + + public String getNighttemp() { + return nighttemp; + } + + public void setNighttemp(String nighttemp) { + this.nighttemp = nighttemp; + } + + public String getDaywind() { + return daywind; + } + + public void setDaywind(String daywind) { + this.daywind = daywind; + } + + public String getNightwind() { + return nightwind; + } + + public void setNightwind(String nightwind) { + this.nightwind = nightwind; + } + + public String getDaypower() { + return daypower; + } + + public void setDaypower(String daypower) { + this.daypower = daypower; + } + + public String getNightpower() { + return nightpower; + } + + public void setNightpower(String nightpower) { + this.nightpower = nightpower; + } +} \ No newline at end of file diff --git a/src/main/java/com/xkrs/utils/CommonConstant.java b/src/main/java/com/xkrs/utils/CommonConstant.java index 19933c7..9573695 100644 --- a/src/main/java/com/xkrs/utils/CommonConstant.java +++ b/src/main/java/com/xkrs/utils/CommonConstant.java @@ -171,7 +171,16 @@ public interface CommonConstant { public static final Integer USER_IDENTITY_1 = 1; public static final Integer USER_IDENTITY_2 = 2; + /** + * 高德天气URL、key + */ + String WEATHER_URL = "https://restapi.amap.com/v3/weather/weatherInfo"; + String WEATHER_KEY = "89d34909932a58c094da0ea390058a12"; - + /** + * 高德逆地理编码 + */ + String INVERSEGEOGRAPHY_URL = "https://restapi.amap.com/v3/geocode/regeo"; + String INVERSEGEOGRAPHY_KEY = "89d34909932a58c094da0ea390058a12"; } diff --git a/src/main/java/com/xkrs/utils/GaoDeApiUtil.java b/src/main/java/com/xkrs/utils/GaoDeApiUtil.java new file mode 100644 index 0000000..8b41514 --- /dev/null +++ b/src/main/java/com/xkrs/utils/GaoDeApiUtil.java @@ -0,0 +1,58 @@ +package com.xkrs.utils; + +import com.alibaba.fastjson.JSON; +import com.xkrs.common.encapsulation.PromptMessageEnum; +import com.xkrs.controller.GaodeApiController; +import com.xkrs.model.vo.GaoDeIgGeocodeVo; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.bind.annotation.RequestBody; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.List; + +import static com.xkrs.common.encapsulation.OutputEncapsulation.outputEncapsulationObject; +import static com.xkrs.utils.CommonConstant.INVERSEGEOGRAPHY_KEY; +import static com.xkrs.utils.CommonConstant.INVERSEGEOGRAPHY_URL; +import static com.xkrs.utils.HttpClientUtils.sendHttpsGet; + +/** + * @author wudong + * @date 2022/5/7 9:45 + * @description + */ +public class GaoDeApiUtil { + private static final Logger log = LoggerFactory.getLogger(GaoDeApiUtil.class); + + /** + * 逆地理编码 + * @param location 示例:["116,23", "117,24"] + * @return + */ + public GaoDeIgGeocodeVo geocode(List location) { + if (location.size() == 0) { + return new GaoDeIgGeocodeVo(){{ + setInfo("参数为空"); + setInfocode("-1");}}; + } + StringBuilder sb = new StringBuilder(); + for (String var : + location) { + sb.append(var).append("|"); + } + String url = INVERSEGEOGRAPHY_URL + "?key=" + INVERSEGEOGRAPHY_KEY + "&radius=1000&extensions=all&batch=true&roadlevel=0&location="; + try { + String encode = URLEncoder.encode(sb.toString(), StandardCharsets.UTF_8); + String res = sendHttpsGet(url + encode); + return JSON.parseObject(res, GaoDeIgGeocodeVo.class); + } catch (Exception e) { + log.error("获取高德天气失败, {}", e.getMessage()); + } + return new GaoDeIgGeocodeVo(){{ + setInfo("获取高德天气失败"); + setInfocode("-1"); + }}; + } + +} diff --git a/src/main/java/com/xkrs/utils/HttpClientUtils.java b/src/main/java/com/xkrs/utils/HttpClientUtils.java new file mode 100644 index 0000000..2129b97 --- /dev/null +++ b/src/main/java/com/xkrs/utils/HttpClientUtils.java @@ -0,0 +1,193 @@ +package com.xkrs.utils; + +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpRequestBase; +import org.apache.http.config.Registry; +import org.apache.http.config.RegistryBuilder; +import org.apache.http.conn.socket.ConnectionSocketFactory; +import org.apache.http.conn.socket.PlainConnectionSocketFactory; +import org.apache.http.conn.ssl.NoopHostnameVerifier; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.conn.ssl.TrustSelfSignedStrategy; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.apache.http.ssl.SSLContexts; +import org.apache.http.util.EntityUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; +import java.security.KeyManagementException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; + +/** + * http工具类 + */ +public class HttpClientUtils { + + private static final Logger log = LoggerFactory.getLogger(HttpClientUtils.class); + + /** + * 发送http+get请求 + * @param url + * @return 返回结果 + * @throws Exception + */ + public static String sendHttpGet(String url) throws Exception { + CloseableHttpClient httpClient = HttpClients.createDefault(); + return doGet(url,httpClient); + } + + /** + * 发送https+get请求,绕过证书 + * @param url 请求地址 + * @return 返回结果 + * @throws Exception + */ + public static String sendHttpsGet(String url) throws Exception { +// CloseableHttpClient httpClient = createIgnoreVerifyHttpClient(); + //CloseableHttpClient httpClient = HttpClients.createDefault(); + SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory( + SSLContexts.custom() + .loadTrustMaterial(null, new TrustSelfSignedStrategy()) + .build(), + NoopHostnameVerifier.INSTANCE + ); + CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(scsf).build(); + return doGet(url,httpClient); + } + + /** + * 发送http+post请求 + * @param url 请求地址 + * @param params 请求参数 json字符串 + * @return 返回结果 + * @throws Exception + */ + public static String sendHttpPost(String url, String params) throws Exception { + CloseableHttpClient httpClient = HttpClients.createDefault(); + return doPost(httpClient, url, params); + } + + /** + * 发送https+post请求 + * @param url 请求地址 + * @param params 请求参数 json字符串 + * @return 返回结果 + * @throws Exception + */ + public static String sendHttpsPost(String url, String params) throws Exception { + // CloseableHttpClient httpClient = createIgnoreVerifyHttpClient(); + // CloseableHttpClient httpClient = null; + SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory( + SSLContexts.custom() + .loadTrustMaterial(null, new TrustSelfSignedStrategy()) + .build(), + NoopHostnameVerifier.INSTANCE + ); + CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(scsf).build(); + // CloseableHttpClient httpClient = HttpClients.createDefault(); + return doPost(httpClient, url, params); + + } + + /** + * 封装get请求方式的处理 + */ + private static String doGet(String url,CloseableHttpClient httpClient) throws Exception { + log.info("HGet请求url={}", url); + HttpGet httpGet = new HttpGet(url); + return execute(httpClient,httpGet); + } + + /** + * 封装post请求方式的处理 + */ + private static String doPost(CloseableHttpClient httpClient, String url, String params) throws Exception { + log.info("Post请求url:{}", url); + log.info("Post请求params:{}", params); + HttpPost httpPost = new HttpPost(url); + httpPost.addHeader("Content-Type", "application/json; charset=utf-8"); + httpPost.setEntity(new StringEntity(params)); + return execute(httpClient,httpPost); + } + + /** + * 执行发送 + */ + private static String execute(CloseableHttpClient httpClient, HttpRequestBase requestBase) throws Exception { + String result = null; + CloseableHttpResponse response = null; + try { + response = httpClient.execute(requestBase); + int statusCode = response.getStatusLine().getStatusCode(); + log.info("HttpClient响应码={}", statusCode); + final int success = 200; + if (statusCode == success) { + result = EntityUtils.toString(response.getEntity(),"utf-8"); + } else { + log.error("HttpClient请求失败,错误码={}", statusCode); + } + } catch (Exception e) { + log.error("HttpClient请求异常:", e); + } finally { + if (null != httpClient) { + httpClient.close(); + } + if (null != response) { + response.close(); + } + } + log.info("HttpClient请求结果:{}", result); + return result; + } + + /** + * 绕过验证 + * + * @return + * @throws NoSuchAlgorithmException + * @throws KeyManagementException + */ + public static CloseableHttpClient createIgnoreVerifyHttpClient() throws Exception { + SSLContext sslContext = SSLContext.getInstance("TLS"); + // 实现一个X509TrustManager接口 + X509TrustManager trustManager = new X509TrustManager() { + @Override + public void checkClientTrusted( + X509Certificate[] paramArrayOfX509Certificate, + String paramString) throws CertificateException { + } + + @Override + public void checkServerTrusted( + X509Certificate[] paramArrayOfX509Certificate, + String paramString) throws CertificateException { + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return null; + } + }; + sslContext.init(null, new TrustManager[]{trustManager}, null); + Registry socketFactoryRegistry = + RegistryBuilder.create() + .register("http", PlainConnectionSocketFactory.INSTANCE) + .register("https", new SSLConnectionSocketFactory(sslContext)).build(); + PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); + CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).build(); + return httpClient; + } + +} + +