package com.jilongda.common.utils; import com.alibaba.fastjson.JSONObject; import com.jilongda.common.exception.ServiceException; import lombok.extern.slf4j.Slf4j; import org.apache.http.Consts; import org.apache.http.HttpStatus; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.apache.http.util.TextUtils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; /** * @Description * @Author xiaochen * @Date 2021/11/30/03020:51 */ @Slf4j public class HttpClientUtil { public static String post(String strURL, String params, String token) { System.out.println(strURL); System.out.println(params); String result = ""; BufferedReader reader = null; try { URL url = new URL(strURL);// 创建连接 HttpURLConnection connection = (HttpURLConnection) url .openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestMethod("POST"); // 设置请求方式 connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式 connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式 connection.setRequestProperty("Authorization", token); // 设置token connection.connect(); if (params != null && !TextUtils.isEmpty(params)) { byte[] writebytes = params.getBytes(); // 设置文件长度 // connection.setRequestProperty("Content-Length", String.valueOf(writebytes.length)); OutputStream outwritestream = connection.getOutputStream(); outwritestream.write(params.getBytes()); outwritestream.flush(); outwritestream.close(); // Log.d("hlhupload", "doJsonPost: conn"+connection.getResponseCode()); } if (connection.getResponseCode() == 200) { log.info("<<<<<<<<<<<<<请求响应错误信息:{}", connection.getResponseMessage()); reader = new BufferedReader( new InputStreamReader(connection.getInputStream())); result = reader.readLine(); log.info("<<<<<<<<<<<<<请求响应:{}", result); } else { throw new ServiceException(connection.getResponseMessage()); } } catch (Exception e) { throw new ServiceException("http的post请求异常!" + e.getMessage()); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; } /** * 请求发送执行 * * @param httpMethd * @return */ /** * PSOT JSON方式提交 * * @param url 请求url * @param params json串 * @return */ public static String postFromJson(String url, String params, String token) { HttpPost request = new HttpPost(url); request.setHeader("Content-type", "application/json"); request.setHeader("Accept", "application/json"); request.setHeader("Authorization", token); RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(12000) .setConnectTimeout(8000) .build(); request.setConfig(requestConfig); StringEntity entity = new StringEntity(params, StandardCharsets.UTF_8); entity.setContentType("application/json"); request.setEntity(entity); CloseableHttpClient httpClient = HttpClients.createDefault(); try (CloseableHttpResponse httpResponse = httpClient.execute(request, HttpClientContext.create())) { int statusCode = httpResponse.getStatusLine().getStatusCode(); if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { log.error("响应失败 statusCode:{}", statusCode); String result = EntityUtils.toString(httpResponse.getEntity(), Consts.UTF_8); JSONObject jsonObject = JSONObject.parseObject(result); String message = jsonObject.getString("message"); throw new ServiceException(message); } else { String response = EntityUtils.toString(httpResponse.getEntity(), Consts.UTF_8); log.info("响应成功 response {}", response); return response; } } catch (Exception e) { throw new RuntimeException(e.getMessage()); } } }