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


http状态码

http状态信息

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐