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,这样不容易看懂。