HttpClient4.3.3 禁止自动重定向
HttpClient4.3中默认允许自动重定向,导致程序中不能跟踪跳转情况,其实只需要在RequestConfig中setRedirectsEnabled(false)即可(默认是true):另外如发生重定向,response的状态码为302,不是200。HttpStatus.SC_MOVED_TEMPORARILYpublic class CustomerGateway impl
·
HttpClient4.3中默认允许自动重定向,导致程序中不能跟踪跳转情况,其实只需要在RequestConfig中setRedirectsEnabled(false)即可(默认是true):
另外如发生重定向,response的状态码为302,不是200。
HttpStatus.SC_MOVED_TEMPORARILY
public class CustomerGateway implements Gateway, InitializingBean, DisposableBean {
private Logger logger = LoggerFactory.getLogger(this.getClass());
private CloseableHttpClient httpClient;
@Override
public void afterPropertiesSet() throws Exception {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
// Increase max total connection to 200
cm.setMaxTotal(200);
// Increase default max connection per route to 20
cm.setDefaultMaxPerRoute(100);
httpClient = HttpClients
.custom()
.setDefaultRequestConfig(
RequestConfig.custom().setSocketTimeout(25000)
.setConnectTimeout(15000)
.setConnectionRequestTimeout(15000)
.setRedirectsEnabled(false).build())
.setConnectionManager(cm).build();
}
@Override
public void destroy() throws Exception {
httpClient.close();
}
@Override
public Object send(Object packet, String id) throws CommunicationException {
throw new UnsupportedOperationException();
}
@Override
public Object receive(Object hint, String id) throws CommunicationException {
throw new UnsupportedOperationException();
}
@Override
public Object sendAndReceive(Object request, String id)
throws CommunicationException {
CloseableHttpResponse response = null;
HttpUriRequest hRequest = (HttpUriRequest) request;
try {
response = httpClient.execute(hRequest);
if (HttpStatus.SC_MOVED_TEMPORARILY == response.getStatusLine().getStatusCode()) {
return response.getFirstHeader("Location").getValue();
} else {
throw new CommunicationException(false,
"response invalidated response code is "
+ response.getStatusLine().getStatusCode());
}
} catch (ConnectTimeoutException e) {
throw new CommunicationException(true, "connect_time_out", e);
} catch (SocketTimeoutException e) {
throw new CommunicationException(true, "read_time_out", e);
} catch (Exception e) {
throw new CommunicationException(false, "request error", e);
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
logger.error("http gateway response close error!", e);
}
}
}
}
}
更多推荐
已为社区贡献1条内容
所有评论(0)