1、引入资源
<!-- httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
2、创建公共帮助类
import com.bo.HttpResponseBO;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.*;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.io.StringWriter;
import java.util.Map;
public class HttpClientUtils {
/**
* get 请求
*
* @param url 地址
* @return 请求结果
* @throws Exception 异常信息
*/
public static HttpResponseBO get(String url) throws Exception {
return get(url, null);
}
/**
* get 请求
*
* @param url 地址
* @param header 头部信息
* @return 请求结果
* @throws Exception 异常信息
*/
public static HttpResponseBO get(String url, Map<String, String> header) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
if (MapUtils.isNotEmpty(header)) {
for (Map.Entry<String, String> entry : header.entrySet()) {
httpGet.addHeader(entry.getKey(), entry.getValue());
}
}
CloseableHttpResponse response = httpClient.execute(httpGet);
HttpResponseBO responseBO = new HttpResponseBO();
try {
responseBO.setCode(response.getStatusLine().getStatusCode());
StringWriter stringWriter = new StringWriter();
if (response.getEntity() != null) {
IOUtils.copy(response.getEntity().getContent(), stringWriter, "UTF8");
}
responseBO.setContent(stringWriter.toString());
} finally {
if (null != httpClient) {
httpClient.close();
}
if (null != response) {
response.close();
}
return responseBO;
}
}
/**
* post 请求
*
* @param url 地址
* @param body body参数
* @param contentType 请求类型
* @return 请求结果
* @throws Exception 异常信息
*/
public static HttpResponseBO post(String url, String body, ContentType contentType) throws Exception {
return post(url, body, null, contentType);
}
/**
* post 请求
*
* @param url 地址
* @param body body参数
* @param contentType 请求类型
* @return 请求结果
* @throws Exception 异常信息
*/
public static HttpResponseBO post(String url, String body, Map<String, String> header, ContentType contentType) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
if (body != null) {
StringEntity stringEntity = new StringEntity(body, contentType);
httpPost.setEntity(stringEntity);
}
if (MapUtils.isNotEmpty(header)) {
for (Map.Entry<String, String> entry : header.entrySet()) {
httpPost.addHeader(entry.getKey(), entry.getValue());
}
}
CloseableHttpResponse response = httpClient.execute(httpPost);
HttpResponseBO responseBO = new HttpResponseBO();
try {
responseBO.setCode(response.getStatusLine().getStatusCode());
StringWriter stringWriter = new StringWriter();
if (response.getEntity() != null) {
IOUtils.copy(response.getEntity().getContent(), stringWriter, "UTF8");
}
responseBO.setContent(stringWriter.toString());
} finally {
if (null != httpClient) {
httpClient.close();
}
if (null != response) {
response.close();
}
return responseBO;
}
}
/**
* post 请求
*
* @param url 地址
* @param body body参数
* @return 请求结果
* @throws Exception 异常信息
*/
public static HttpResponseBO post(String url, String body, Map<String, String> header, String charset) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
if (body != null) {
StringEntity stringEntity = new StringEntity(body, charset);
httpPost.setEntity(stringEntity);
}
if (MapUtils.isNotEmpty(header)) {
for (Map.Entry<String, String> entry : header.entrySet()) {
httpPost.addHeader(entry.getKey(), entry.getValue());
}
}
CloseableHttpResponse response = httpClient.execute(httpPost);
HttpResponseBO responseBO = new HttpResponseBO();
try {
responseBO.setCode(response.getStatusLine().getStatusCode());
StringWriter stringWriter = new StringWriter();
if (response.getEntity() != null) {
IOUtils.copy(response.getEntity().getContent(), stringWriter, "UTF8");
}
responseBO.setContent(stringWriter.toString());
} finally {
if (null != httpClient) {
httpClient.close();
}
if (null != response) {
response.close();
}
return responseBO;
}
}
/**
* put 请求
*
* @param url 地址
* @param body body参数
* @param header 请求头
* @param contentType 编码
* @return 请求结果
* @throws Exception 异常信息
*/
public static HttpResponseBO put(String url, String body, Map<String, String> header, ContentType contentType) throws Exception {
if (contentType != null) {
contentType = ContentType.APPLICATION_JSON;
}
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPut httpPut = new HttpPut(url);
if (body != null) {
StringEntity stringEntity = new StringEntity(body, contentType);
httpPut.setEntity(stringEntity);
}
if (MapUtils.isNotEmpty(header)) {
for (Map.Entry<String, String> entry : header.entrySet()) {
httpPut.addHeader(entry.getKey(), entry.getValue());
}
}
CloseableHttpResponse response = httpClient.execute(httpPut);
HttpResponseBO responseBO = new HttpResponseBO();
try {
responseBO.setCode(response.getStatusLine().getStatusCode());
StringWriter stringWriter = new StringWriter();
if (response.getEntity() != null) {
IOUtils.copy(response.getEntity().getContent(), stringWriter, "UTF8");
}
responseBO.setContent(stringWriter.toString());
} finally {
if (null != httpClient) {
httpClient.close();
}
if (null != response) {
response.close();
}
return responseBO;
}
}
/**
* delete 请求
*
* @param url 地址
* @param header 请求头
* @param charset 编码
* @return 请求结果
* @throws Exception 异常信息
*/
public static HttpResponseBO delete(String url, Map<String, String> header, String charset) throws Exception {
if (StringUtils.isBlank(charset)) {
charset = "UTF8";
}
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpDelete httpDelete = new HttpDelete(url);
if (MapUtils.isNotEmpty(header)) {
for (Map.Entry<String, String> entry : header.entrySet()) {
httpDelete.addHeader(entry.getKey(), entry.getValue());
}
}
CloseableHttpResponse response = httpClient.execute(httpDelete);
HttpResponseBO responseBO = new HttpResponseBO();
try {
responseBO.setCode(response.getStatusLine().getStatusCode());
StringWriter stringWriter = new StringWriter();
if (response.getEntity() != null) {
IOUtils.copy(response.getEntity().getContent(), stringWriter, charset);
}
responseBO.setContent(stringWriter.toString());
} finally {
if (null != httpClient) {
httpClient.close();
}
if (null != response) {
response.close();
}
return responseBO;
}
}
}
3、创建对象接收调用结果信息
import lombok.Data;
@Data
public class HttpResponseBO {
/**
* 响应码
*/
private int code;
/**
* 响应内容
*/
private String content;
}
使用过程中碰到的问题
java.net.SocketException: Broken pipe (Write failed)
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:111)
at java.net.SocketOutputStream.write(SocketOutputStream.java:155)
at sun.security.ssl.OutputRecord.writeBuffer(OutputRecord.java:431)
at sun.security.ssl.OutputRecord.write(OutputRecord.java:417)
at sun.security.ssl.SSLSocketImpl.writeRecordInternal(SSLSocketImpl.java:876)
at sun.security.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:847)
at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:123)
at org.apache.http.impl.io.SessionOutputBufferImpl.streamWrite(SessionOutputBufferImpl.java:124)
at org.apache.http.impl.io.SessionOutputBufferImpl.write(SessionOutputBufferImpl.java:160)
at org.apache.http.impl.io.ContentLengthOutputStream.write(ContentLengthOutputStream.java:113)
at org.apache.http.impl.io.ContentLengthOutputStream.write(ContentLengthOutputStream.java:120)
at org.apache.http.entity.StringEntity.writeTo(StringEntity.java:167)
at org.apache.http.impl.DefaultBHttpClientConnection.sendRequestEntity(DefaultBHttpClientConnection.java:156)
at org.apache.http.impl.conn.CPoolProxy.sendRequestEntity(CPoolProxy.java:160)
at org.apache.http.protocol.HttpRequestExecutor.doSendRequest(HttpRequestExecutor.java:238)
at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:123)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:272)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:185)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:111)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:108)
at com.util.HttpClientUtils.put(HttpClientUtils.java:192)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:749)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.validation.beanvalidation.MethodValidationInterceptor.invoke(MethodValidationInterceptor.java:119)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:749)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.validation.beanvalidation.MethodValidationInterceptor.invoke(MethodValidationInterceptor.java:119)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:892)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1039)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:96)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:853)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1587)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
在本项目出现问题的原因(本地和测试环境正常,正式环境出现): TIME_WAIT 过多导致
1、查看服务器连接信息
参考:https://blog.csdn.net/hightrees/article/details/78608811
原因 TIME_WAIT 过多,默认60s,导致连接失败,修改响应参数
参考地址:https://blog.csdn.net/twt936457991/article/details/90574284 进行修改
如果项目使用HttpClient量比较多,建议使用 HttpAsynClient ,这个使用HttpClient和nio进行异步操作,效率比HttpClient好,因为服务器访问量大的话很容易报错 可以参考 https://blog.csdn.net/fengxing_2/article/details/103399913 切换也比较容易