|
@@ -156,6 +156,59 @@ public class HttpClientUtil {
|
|
|
|
|
|
|
|
|
/**
|
|
|
+ * 发送HTTP POST请求,使用String类型作为请求体参数
|
|
|
+ * @param url 请求URL
|
|
|
+ * @param params 请求体参数(通常为JSON字符串)
|
|
|
+ * @param headers 请求头信息
|
|
|
+ * @return 响应结果字符串
|
|
|
+ * @throws Exception 可能抛出的异常
|
|
|
+ */
|
|
|
+ public static String httpPost201(String url, String params, HashMap<String, String> headers) throws Exception {
|
|
|
+ String result = "";
|
|
|
+ CloseableHttpClient httpClient = HttpClients.createDefault();
|
|
|
+ HttpPost httpPost = new HttpPost(url);
|
|
|
+
|
|
|
+ // 设置最大请求和传输超时时间
|
|
|
+ RequestConfig requestConfig = RequestConfig.custom()
|
|
|
+ .setSocketTimeout(50000)
|
|
|
+ .setConnectTimeout(50000)
|
|
|
+ .build();
|
|
|
+ httpPost.setConfig(requestConfig);
|
|
|
+
|
|
|
+ // 设置请求头
|
|
|
+ if (headers != null && !headers.isEmpty()) {
|
|
|
+ for (String key : headers.keySet()) {
|
|
|
+ httpPost.addHeader(key, headers.get(key));
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ // 设置请求体参数
|
|
|
+ if (params != null && !params.isEmpty()) {
|
|
|
+ // 使用StringEntity直接设置字符串作为请求体
|
|
|
+ StringEntity stringEntity = new StringEntity(params, StandardCharsets.UTF_8);
|
|
|
+ httpPost.setEntity(stringEntity);
|
|
|
+ }
|
|
|
+
|
|
|
+ CloseableHttpResponse response = httpClient.execute(httpPost);
|
|
|
+
|
|
|
+ try {
|
|
|
+ if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
|
|
|
+ HttpEntity entity = response.getEntity();
|
|
|
+ result = EntityUtils.toString(entity, StandardCharsets.UTF_8);
|
|
|
+ EntityUtils.consume(entity);
|
|
|
+ } else {
|
|
|
+ throw new Exception(response.getStatusLine().toString());
|
|
|
+ }
|
|
|
+ } finally {
|
|
|
+ response.close();
|
|
|
+ httpClient.close();
|
|
|
+ }
|
|
|
+ return result;
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+ /**
|
|
|
* http POST 请求,支持自定义请求头
|
|
|
*
|
|
|
* @param url 请求URL
|