public class HttpRequstUtil {/*** http請求方法** @param message 查詢條件* @param url 查詢地址* @param token 身份驗證token* @param socketTimeout socket 響應時間* @param connectTimeout 超時時間* @return 返回字符串*/@Deprecatedpublic static String queryResultToString(JSON message, String url, String token, int socketTimeout, int connectTimeout) throws Exception {/*System.out.println("->開始http請求");System.out.println("請求參數>>>" + message.toString());System.out.println("請求鏈接>>>" + url);System.out.println("請求token>>>" + token);System.out.println("超時配置socketTimeout-connectTimeout>>>" + socketTimeout + "-" + connectTimeout);*/String result = "";// 轉碼 將發送的數據轉為字符串實體StringEntity outEntity = new StringEntity(message.toString(), "UTF-8");outEntity.setContentType("application/json");//System.out.println("請求數據轉碼>>>" + outEntity.toString());// 配置請求項RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();//System.out.println("請求配置項>>>" + requestConfig.toString());// 配置請求頭HttpPost httpPost = new HttpPost(url);httpPost.addHeader("Content-Type", "application/json");httpPost.addHeader("Accept", "application/json");httpPost.addHeader("X-Aa-Token", token);httpPost.setEntity(outEntity);httpPost.setConfig(requestConfig);//System.out.println("http請求信息>>>" + httpPost.toString());try {result = (String) executeRequest(httpPost, true);} catch (Exception e) {throw new Exception(e.toString());}return result;}/*** @param httpRequest* @return java.lang.String* @description 執行Http請求* @date 2022/5/6 20:51*/public static Object executeRequest(HttpUriRequest httpRequest, boolean isStr) throws IOException, DebtException, Exception {Object result = null;// 執行一個http請求,傳遞HttpGet或HttpPost參數CloseableHttpClient httpclient = null;if ("https".equals(httpRequest.getURI().getScheme())) {httpclient = createSSLInsecureClient();} else {httpclient = HttpClients.createDefault();}try {CloseableHttpResponse response = httpclient.execute(httpRequest);//判斷接口是否調用成功int statusCode = response.getStatusLine().getStatusCode();if (HttpStatus.SC_OK != statusCode) {System.out.println("接口調用失敗");throw new ApiException("接口調用失敗,HttpStatus="+statusCode);} else {//System.out.println("發起請求->連接成功");HttpEntity entity = response.getEntity();// 是-獲取字符串 否-獲取字節數組if (isStr) {result = EntityUtils.toString(entity, "UTF-8");} else {result = EntityUtils.toByteArray(entity);}// 關閉資源EntityUtils.consume(entity);}} catch (Exception e) {throw new Exception(e.toString());} finally {try {httpclient.close();} catch (IOException e) {throw new IOException(e.toString());}}return result;}/*** 創建 SSL連接*/private static CloseableHttpClient createSSLInsecureClient() throws Exception {try {SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(new TrustStrategy() {@Overridepublic boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {return true;}}).build();SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new HostnameVerifier() {@Overridepublic boolean verify(String hostname, SSLSession session) {return true;}});return HttpClients.custom().setSSLSocketFactory(sslsf).build();} catch (GeneralSecurityException ex) {throw new RuntimeException(ex);}}/*** @description 通過POST方式發送JSON數據* @author wangws* @date 2022/9/7 12:54* @param url 請求路徑* @param message 待發送JSON信息* @param isStr 是否返回字符串(否,返回字節數組)* @param header 請求頭Header(設置Token等)* @param timeOut 超時時間設置(socketTimeout,connectTimeout)* @return java.lang.Object*/public static Object sendJsonByPost(String url, JSON message, boolean isStr, Map<String, String> header, Map<String, Integer> timeOut) throws Exception {Object result = null;// 1.創建http請求對象Object httpRequestObj = createHttpRequest("POST");if (!StringTool.isNull(httpRequestObj)) {HttpPost httpPost = (HttpPost) httpRequestObj;// 2.添加URLhttpPost.setURI(URI.create(url));// 無需設置Header的Content-Type// 3.設置其他請求頭信息if (!StringTool.isNull(header)) {Iterator<Map.Entry<String, String>> iterator = header.entrySet().iterator();while (iterator.hasNext()) {Map.Entry<String, String> next = iterator.next();httpPost.addHeader(next.getKey(), next.getValue());}}// 添加JSON信息// 將發送的數據轉為字符串實體StringEntity entity = new StringEntity(message.toString(), "UTF-8");entity.setContentType("application/json;charset=UTF-8");// 4.設置消息體httpPost.setEntity(entity);RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeOut.get("socketTimeout")).setConnectTimeout(timeOut.get("connectTimeout")).build();// 5.設置請求配置項httpPost.setConfig(requestConfig);// 6.執行Http請求對象,返回結果result = executeRequest(httpPost, isStr);} else {throw new ApiException("Http Request Method is not be matched");}return result;}/*** @param path 請求路徑* @param message Get請求參數* @param isStr 是否返回字符串(否,返回字節數組)* @param header 請求頭Header(設置Token等)* @param timeOut 超時時間設置(socketTimeout,connectTimeout)* @return java.lang.Object* @description 通過GET方式請求數據* @author wangws* @date 2022/10/18 12:54*/public static Object sendDataByGet(String path, Map<String, String> message, boolean isStr, Map<String, String> header, Map<String, Integer> timeOut) throws Exception {Object result = null;// 1.創建http請求對象Object httpRequestObj = createHttpRequest("GET");if (!StringTool.isNull(httpRequestObj)) {HttpGet httpGet = (HttpGet) httpRequestObj;StringBuilder urlBuilder = new StringBuilder();// 設置接口地址urlBuilder.append(path);URIBuilder uri = new URIBuilder();// 設置網絡協議//uri.setScheme("https");// 設置主機地址//uri.setHost("www.baidu.com");// 設置方法//uri.setPath("/getdata");//添加參數// 2.拼接GET請求參數if (!StringTool.isNull(message) && !message.isEmpty()) {Iterator<Map.Entry<String, String>> it = message.entrySet().iterator();while (it.hasNext()) {Map.Entry<String, String> next = it.next();uri.setParameter(next.getKey(), next.getValue());}}urlBuilder.append(uri.build().toString());// 3.添加URLhttpGet.setURI(new URI(urlBuilder.toString()));// 4.設置其他請求頭信息if (!StringTool.isNull(header)) {Iterator<Map.Entry<String, String>> iterator = header.entrySet().iterator();while (iterator.hasNext()) {Map.Entry<String, String> next = iterator.next();httpGet.addHeader(next.getKey(), next.getValue());}}RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeOut.get("socketTimeout")).setConnectTimeout(timeOut.get("connectTimeout")).build();// 5.設置請求配置項httpGet.setConfig(requestConfig);// 6.執行Http請求對象,返回結果result = executeRequest(httpGet, isStr);} else {throw new Exception("Http Request Method is not be matched");}return result;}/*** @description 通過POST方式上傳文件* @author wangws* @date 2022/9/7 12:55* @param url 請求路徑* @param file 待上傳文件* @param isStr 是否返回字符串(否,返回字節數組)* @param header 請求頭Header* @param param 待發送參數信息* @param timeOut 超時時間設置(socketTimeout,connectTimeout)* @return java.lang.Object*/public static Object uploadFileByPost(String url, File file, boolean isStr, Map<String, String> header, Map<String, String> param, Map<String, Integer> timeOut) throws Exception {Object result = "";// 1.創建http請求對象Object httpRequestObj = createHttpRequest("POST");if (!StringTool.isNull(httpRequestObj)) {HttpPost httpPost = (HttpPost) httpRequestObj;// 2.添加URLhttpPost.setURI(URI.create(url));// 3.追加文件(類似form表單),支持多個// RFC6532 避免文件名為中文時亂碼MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);// 參數名upload(可修改) 注意和后臺接收時保持一致builder.addBinaryBody("upload", file, ContentType.MULTIPART_FORM_DATA, file.getName());builder.setCharset(Charset.forName("UTF-8"));// 無需設置Header的Content-Type,否則會出錯// 4.設置其他請求頭信息if (!StringTool.isNull(header)) {Iterator<Map.Entry<String, String>> iterator = header.entrySet().iterator();while (iterator.hasNext()) {Map.Entry<String, String> next = iterator.next();httpPost.addHeader(next.getKey(), next.getValue());}}// 5.builder添加其他參數信息if (!StringTool.isNull(param)) {Iterator<Map.Entry<String, String>> it = param.entrySet().iterator();while (it.hasNext()) {Map.Entry<String, String> next = it.next();builder.addTextBody(next.getKey(), next.getValue());}}HttpEntity entity = builder.build();// 6.設置消息體httpPost.setEntity(entity);// 7.設置配置項RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeOut.get("socketTimeout")).setConnectTimeout(timeOut.get("connectTimeout")).build();httpPost.setConfig(requestConfig);// 8.執行Http請求對象,返回JSON類型字符串result = executeRequest(httpPost, isStr);} else {throw new ApiException("Http Request Method is not be matched");}// 返回結果return result;}/*** @description 創建HttpRequest請求對象* @author wangws* @date 2022/9/7 12:55* @param requestMethod* @return java.lang.Object*/public static Object createHttpRequest(String requestMethod) {// 大寫轉換requestMethod = requestMethod.toUpperCase();// 設置HTTP的請求方式if ("POST".equals(requestMethod)) {return new HttpPost();} else if ("GET".equals(requestMethod)) {return new HttpGet();} else if ("HEAD".equals(requestMethod)) {return new HttpHead();} else if ("PUT".equals(requestMethod)) {return new HttpPut();} else if ("PATCH".equals(requestMethod)) {return new HttpPatch();} else if ("DELETE".equals(requestMethod)) {return new HttpDelete();} else if ("OPTIONS".equals(requestMethod)) {return new HttpOptions();} else if ("TRACE".equals(requestMethod)) {return new HttpTrace();}return null;}