Java使用HttpClient实现Post请求

本文介绍了如何在Java中利用HttpClient库执行POST请求。详细展示了相关代码,包括HttpClient的依赖引入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

代码实现:

​​​​​​​/**
  * http发送POST请求
  *
  * @author J.M.C
  * @since 2019年1月16日
  * @param url 长连接URL
  * @param paramsJson 请求参数body
  * @return result 字符串
  */
public static String httpPostRequest(String url, JSONObject paramsJson) {
  logger.info("httpPostRequest url : " + url + "   paramMap : " + paramsJson);
  if(StringUtil.isEmptyStr(url)){
    logger.error("httpPostRequest url is null");
    return null;
    }
    String result = "";
  try {
      // 创建httpClient实例
      CloseableHttpClient httpClient = HttpClients.createDefault();
      // 创建httpPost远程连接实例
      HttpPost httpPost = new HttpPost(url);
      // 配置请求参数实例
      RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000)// 设置连接主机服务超时时间
              .setConnectionRequestTimeout(10000)// 设置连接请求超时时间
              .setSocketTimeout(30000)// 设置读取数据连接超时时间
              .build();
      // 为httpPost实例设置配置
      httpPost.setConfig(requestConfig);
      // 设置请求头
      httpPost.addHeader("content-type", "application/json;charset=utf-8");
      // 封装post请求参数
      httpPost.setEntity(new StringEntity(paramsJson.toJSONString(), Charset.forName("UTF-8")));
   // httpClient对象执行post请求,并返回响应参数对象
   ~~//   HttpResponse httpResponse = httpClient.execute(httpPost);~~ 
      CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
   // 从响应对象中获取响应内容
   result = EntityUtils.toString(httpResponse.getEntity());
  } catch (UnsupportedEncodingException e) {
      logger.error("URLUtil.httpPostRequest encounters an UnsupportedEncodingException : {}",e);
    } catch (IOException e) {
      logger.error("URLUtil.httpPostRequest encounters an IOException : {}",e);
    }
  logger.info("URLUtil.httpPostRequest -----result----: " + result);
    return result;
 }

下面是http依赖

	<dependency>
		<groupId>org.apache.httpcomponents</groupId>
		<artifactId>httpclient</artifactId>
		<version>4.5.2</version>
	</dependency>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值