HttpClient4.3.X 禁止自动重定向

//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);
				}
			}
		}
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值