处理 HttpClient 重定向

2022-08-31 20:43:45

我正在将一些数据POS到正在应答302临时移动的服务器。

我希望HttpClient遵循重定向并自动获取新位置,因为我相信这是HttpClient的默认行为。但是,我收到异常,并且没有遵循重定向:(

以下是相关的代码段,任何想法都将不胜感激:

HttpParams httpParams = new BasicHttpParams();
HttpClientParams.setRedirecting(httpParams, true);
SchemeRegistry schemeRegistry = registerFactories();
ClientConnectionManager clientConnectionManager = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

HttpClient httpClient = new DefaultHttpClient(clientConnectionManager, httpParams)
HttpPost postRequest = new HttpPost(url);
postRequest.setHeader(HTTP.CONTENT_TYPE, contentType);
postRequest.setHeader(ACCEPT, contentType);

if (requestBodyString != null) {
    postRequest.setEntity(new StringEntity(requestBodyString));
}

return httpClient.execute(postRequest, responseHandler);

答案 1

对于 HttpClient 4.3

HttpClient instance = HttpClientBuilder.create()
                     .setRedirectStrategy(new LaxRedirectStrategy()).build();

对于 httpClient 4.2

DefaultHttpClient client = new DefaultHttpClient();
client.setRedirectStrategy(new LaxRedirectStrategy());

对于 httpClient < 4.2:

DefaultHttpClient client = new DefaultHttpClient();
client.setRedirectStrategy(new DefaultRedirectStrategy() {
    /** Redirectable methods. */
    private String[] REDIRECT_METHODS = new String[] { 
        HttpGet.METHOD_NAME, HttpPost.METHOD_NAME, HttpHead.METHOD_NAME 
    };

    @Override
    protected boolean isRedirectable(String method) {
        for (String m : REDIRECT_METHODS) {
            if (m.equalsIgnoreCase(method)) {
                return true;
            }
        }
        return false;
    }
});

答案 2

HttpClient 的默认行为符合 HTTP 规范 (RFC 2616) 的要求

10.3.3 302 Found
...

   If the 302 status code is received in response to a request other
   than GET or HEAD, the user agent MUST NOT automatically redirect the
   request unless it can be confirmed by the user, since this might
   change the conditions under which the request was issued.

您可以通过对 DefaultRedirectStrategy 进行子类化并重写其 #isRedirected() 方法来覆盖 HttpClient 的默认行为。


推荐