HttpClient重定向

HttpClient Redirects Handling

简介

这份文档简单介绍下HttpClient手动处理重定向功能。



因为某些原因,比如需要人工的支持或者HttpClient不支持又或者网络的限制(如需要特殊的权限才可以访问的资源),有些类型的重定向是HttpClient不能自动处理的。当前版本的HttpClient不能够自动处理POST和PUT方法的重定向。

手动处理重定向

介于300和399之间的状态码,都代表重定向。最常见的重定向状态码如下:

·       301 HttpStatus.SC_MOVED_PERMANENTLY,永久移除。

·       302 HtpStatus.SC_MOVED_TEMPORARILY,暂时移除。

·       303 HttpStatus.SC_SEE_OTHER,重定向到其他资源。

·       307 HttpStatus.SC_TEMPORARY_REDIRECT,临时重定向。

注意:有些3XX的状态码并不只是简单给发送请求标识一个不同的URL。这些状态码需要应用自行处理。



当应用程序收个一个简单的重定向Responses时,必须用新的URL去执行HttpMethod的executeMethod方法,重新下载新URL对应的资源。通常,我们采用递归的方式去处理重定向,以防有多个重定向,不过要加标识数去结束你的递归。



String redirectLocation;

        Header locationHeader = method.getResponseHeader("location");

        if (locationHeader != null) {

            redirectLocation = locationHeader.getValue();

        } else {

            // The response is invalid and did not provide the new location for

            // the resource.  Report an error or possibly handle the response

            // like a 404 Not Found error.

        }

String redirectLocation;

        Header locationHeader = method.getResponseHeader("location");

        if (locationHeader != null) {

            redirectLocation = locationHeader.getValue();

        } else {

            // The response is invalid and did not provide the new location for

            // the resource.  Report an error or possibly handle the response

            // like a 404 Not Found error.

        }


当得到新的Location以后,你可以对待一个新的URL一样,使用HttpClient去请求对应的资源。

【转载地址】http://blog.csdn.net/mgoann/article/details/4058756

猜你喜欢

转载自hck.iteye.com/blog/1698052