处理HttpClient重定向 [英] Handling HttpClient Redirects

查看:104
本文介绍了处理HttpClient重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一些数据发布到正在回复302暂时移动的服务器。

I'm POSTing some data to a server that is answering a 302 Moved Temporarily.

我希望HttpClient遵循重定向并自动获取新位置,如我相信这是HttpClient的默认行为。但是,我得到了一个例外而没有遵循重定向:(

I want HttpClient to follow the redirect and automatically GET the new location, as I believe it's the default behaviour of HttpClient. However, I'm getting an exception and not following the redirect :(

这是相关的代码段,任何想法都将受到赞赏:

Here's the relevant piece of code, any ideas will be appreciated:

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


推荐答案

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

The default behaviour of HttpClient is compliant with the requirements of the HTTP specification (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的默认行为。

You can override the default behaviour of HttpClient by sub-classing DefaultRedirectStrategy and overriding its #isRedirected() method.

这篇关于处理HttpClient重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆