• httpClientUtil的post请求


    post请求的写法,带请求头和请求体:

    代码:

     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.HttpPost;
     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 HttpRequestPostServiceImpl implements HttpRequestPostService {
    17     CloseableHttpClient httpClient = HttpClients.createDefault();
    18 
    19     @Override
    20     public String doPostHttpRequest(String url, Map<String, String> headerMap, String requestBody) {
    21         String entityStr = null;
    22         CloseableHttpResponse response = null;
    23         try {
    24             HttpPost post = new HttpPost(url);
    25             //添加头部信息
    26             for (Map.Entry<String, String> header : headerMap.entrySet()) {
    27                 post.addHeader(header.getKey(), header.getValue());
    28             }
    29             HttpEntity entity = new StringEntity(requestBody, "Utf-8");
    30             System.out.println("请求体是:" + requestBody);
    31             post.setEntity(entity);
    32             response = httpClient.execute(post);
    33             // 获得响应的实体对象
    34             HttpEntity httpEntity = response.getEntity();
    35             // 使用Apache提供的工具类进行转换成字符串
    36             entityStr = EntityUtils.toString(httpEntity, "UTF-8");
    37             System.out.println("POST请求路径:" + post);
    38             System.out.println("POST请求结果:" + entityStr);
    39         } catch (ClientProtocolException e) {
    40             System.err.println("Http协议出现问题");
    41             e.printStackTrace();
    42         } catch (ParseException e) {
    43             System.err.println("解析错误");
    44             e.printStackTrace();
    45         } catch (IOException e) {
    46             System.err.println("IO异常");
    47             e.printStackTrace();
    48         }
    49         return entityStr;
    50     }
    51 }
  • 相关阅读:
    强大的js时间选择器 万年历
    js 锚点平滑定位
    php str_replace的替换漏洞
    绝对路径 相对路径 小结
    昨天去了长城
    [转载]71个做饭技巧好好记住了,不要忘记给自己做一顿美餐噢
    最近心情很糟,情绪很低落
    用javascript实现html页面之间的参数传递的四种方法
    解决ajax缓存问题
    [转载]30岁前男人需要完成的事
  • 原文地址:https://www.cnblogs.com/wangquanyi/p/11328847.html
Copyright © 2020-2023  润新知