httpClientUtil的put请求

httpClientUtil的put请求,含请求头和请求体:

代码:

 1 import org.apache.http.HttpEntity;
 2 import org.apache.http.ParseException;
 3 import org.apache.http.client.ClientProtocolException;
 4 import org.apache.http.client.methods.CloseableHttpResponse;
 5 import org.apache.http.client.methods.HttpPut;
 6 import org.apache.http.entity.StringEntity;
 7 import org.apache.http.impl.client.CloseableHttpClient;
 8 import org.apache.http.impl.client.HttpClients;
 9 import org.apache.http.util.EntityUtils;
10 import org.springframework.stereotype.Component;
11 
12 import java.io.IOException;
13 import java.util.Map;
14 
15 @Component
16 public class HttpRequestPutServiceImpl {
17     CloseableHttpClient httpClient = HttpClients.createDefault();
18 
19     public String doPutHttpRequest(String url, Map<String, String> headerMap,String requestBody) {
20         String entityStr = null;
21         CloseableHttpResponse response = null;
22         try {
23             HttpPut post = new HttpPut(url);
24             //添加头部信息
25             for (Map.Entry<String, String> header : headerMap.entrySet()) {
26                 post.addHeader(header.getKey(), header.getValue());
27             }
28             HttpEntity entity = new StringEntity(requestBody,"Utf-8");
29             System.out.println("请求体是:"+requestBody);
30             post.setEntity(entity);
31             response = httpClient.execute(post);
32             // 获得响应的实体对象
33             HttpEntity httpEntity = response.getEntity();
34             // 使用Apache提供的工具类进行转换成字符串
35             entityStr = EntityUtils.toString(httpEntity, "UTF-8");
36             System.out.println("PUT请求路径:"+post);
37             System.out.println("PUT请求结果:"+entityStr);
38         } catch (ClientProtocolException e) {
39             System.err.println("Http协议出现问题");
40             e.printStackTrace();
41         } catch (ParseException e) {
42             System.err.println("解析错误");
43             e.printStackTrace();
44         } catch (IOException e) {
45             System.err.println("IO异常");
46             e.printStackTrace();
47         }
48         return entityStr;
49     }
50 }

如有不足之处欢迎大家指导。

转载于:https://www.cnblogs.com/wangquanyi/p/11328868.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值