springboot使用httpclient(PostMethod,RequestEntity等)使用笔记

maven依赖

所需jar包如下:

commons-codec-1.7.jar
commons-logging-1.1.1.jar

commons-httpclient.jar
httpclient-4.2.2.jar
httpcore-4.2.2.jar

如果有spring-boot-starter-parent ,下面2个默认会带:

commons-codec-1.7.jar
commons-logging-1.1.1.jar

所以pom.xml只需要引入如下:

<dependency>
  <groupId>commons-httpclient</groupId>
  <artifactId>commons-httpclient</artifactId>
  <version>3.1</version>
</dependency>
<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.3.1</version>
</dependency>

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpcore</artifactId>
  <version>4.3.1</version>
</dependency>

httpClient设置header

注:setHeader()或者setRequestHeader() 都是会累加的,不用专门弄个header体。

写法一:

HttpPost httpPost = new HttpPost(url);
StringEntity stringEntity = new StringEntity(req, StandardCharsets.UTF_8);
httpPost.setEntity(stringEntity);
httpPost.setHeader("appID", appID);
httpPost.setHeader("customKey", "customValue"); 
response = httpClient.execute(httpPost);

写法二:

PostMethod postMethod = new PostMethod(url);
byte[] b = req.getBytes("utf-8");
InputStream is = new ByteArrayInputStream(b, 0, b.length);
RequestEntity re = new InputStreamRequestEntity(is, b.length,
        "text/xml; charset=utf-8");
postMethod.setRequestHeader("customKey","customValue");
postMethod.setRequestEntity(re);
org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
int statusCode = httpClient.executeMethod(postMethod);

httpclient的异常处理

这个response稍微有点不同。
因为涉及到网络,会有两步,第一步是网络相关,第二部才是数据,所以对response的处理有点不同。

try {
    httpPost.setEntity(new StringEntity(reqData == null ? "" : reqData, StandardCharsets.UTF_8));
    HttpResponse response = httpClient.execute(httpPost);
    if(HttpStatus.SC_OK== response.getStatusLine().getStatusCode()){ // 请求成功
        HttpEntity entity = response.getEntity();
        if (null != entity) {
            reseContent = EntityUtils.toString(entity, ContentType.getOrDefault(entity).getCharset());
            result.getData().add(reseContent);
            EntityUtils.consume(entity); // 释放资源
        }
        logger.info("sendHttp方法完成,返回报文:{}", reseContent);
    }else{ // 请求失败
        logger.info("sendHttp方法失败,状态码非200,response:{}",response.getStatusLine().toString());
        return JsonResult.error("-1",response.getStatusLine().toString());
    }
    return result;
}catch (Exception e) {
    logger.error("sendHttp方法异常,error:", e.toString());
    return JsonResult.error("-1",e.toString());
} finally {
    httpClient.getConnectionManager().shutdown();
}

注:正常来说状态码应该是200,如果是,那么就可以解析内容了。
如果不是,返回状态行信息就行(这里不用返回整个response,多余且查错不好查)

异常处理,用抓其他异常吗?例如ConnectTimeoutException、SocketTimeoutException等。
实际不用的,抓一个Exception就可以,因为会包含那些报错。除非有特殊逻辑,需要精确到具体某种异常。
涉及网络的异常日志,建议用e.toString(),因为一般用e.getMessage()会信息不全。
例如 主机未找到异常,异常信息为:java.net.UnknownHostException: 111api-uat.longfor.com。
如果只用e.getMessage(),只会返回找不到的地址,不会返回java.net.UnknownHostException,这样不容易看懂。

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Spring Boot使用HttpClient可以通过引入httpclient的POM依赖来实现。首先,在你的Spring Boot工程中,需要在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.6</version> </dependency> ``` 接下来,你可以创建一个HttpClientController类,并在该类中定义不同的接口方法,如doGetNoParams和doPostNoParams。这些方法可以使用@GetMapping和@PostMapping注解来标注,分别表示GET和POST请求。例如: ```java @RestController @RequestMapping("/httpClient") public class HttpClientController { @Autowired private HttpClientService httpClientService; // GET请求接口不带参数 @GetMapping("/doGetNoParams") public String doGetNoParams() { return httpClientService.doGetNoParams(); } // POST请求接口不带参数 @PostMapping("/doPostNoParams") public String doPostNoParams() { return httpClientService.doPostNoParams(); } } ``` 在这个示例中,我们使用@Autowired将HttpClientService注入到HttpClientController中,然后在doGetNoParams和doPostNoParams方法中调用相应的HttpClientService方法来实现GET和POST请求。具体的请求逻辑可以在HttpClientService中实现。 这样,你就可以在Spring Boot使用HttpClient来进行HTTP请求了。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [「HttpClient」在 SpringBoot使用 HttpClient 实现 HTTP 请求](https://blog.csdn.net/wdj0311/article/details/121598212)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值