java利用org.apache.http.client.HttpClient发送3种post请求(参数为json、参数为键值对、参数为文件)

//超时时间
private static final int ConnectionRequestTimeout = 5000;//从连接池中获取连接的超时时间
private static final int ConnectTimeout = 60000;//与服务器连接超时时间:httpclient会创建一个异步线程用以创建socket连接,此处设置该socket的连接超时时间
private static final int SocketTimeout = 60000;//socket读数据超时时间:从服务器获取响应数据的超时时间
private static final RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(ConnectionRequestTimeout).setConnectTimeout(ConnectTimeout).setSocketTimeout(SocketTimeout).build();

//发送post请求,参数为键值对
public static Map<String, Object> sendPost(String url, String[] name, String[] value, String[] herderName, String[] headerValue) throws IOException {

    // 获取默认的请求客户端,CloseableHttpClient是HttpClient的实例
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);

    // 设置超时
    httpPost.setConfig(requestConfig);

    //添加herder信息
    for (int i = 0; i < herderNam
  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
可以使用HttpClient类来发送参数POST请求。以下是一个简单的示例代码: ``` import org.apache.http.HttpEntity; 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; public class HttpClientExample { public static void main(String[] args) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://example.com/api/post"); StringEntity entity = new StringEntity("param1=value1&param2=value2"); httpPost.setEntity(entity); httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-type", "application/x-www-form-urlencoded"); CloseableHttpResponse response = httpClient.execute(httpPost); HttpEntity responseEntity = response.getEntity(); System.out.println(EntityUtils.toString(responseEntity)); response.close(); httpClient.close(); } } ``` 在上面的代码中,我们创建了一个`CloseableHttpClient`对象,并使用`HttpPost`类来发送POST请求请求地址为`http://example.com/api/post`。我们使用`StringEntity`类来封装请求参数,并通过设置请求头来告诉服务器请求内容的类型。最后,我们使用`CloseableHttpResponse`对象获取服务器的响应,并通过`EntityUtils.toString`方法将响应内容转换为字符串。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

萌翻天

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值