---
title: "HttpClient重定向"
author: "mgoann"
date: "2009-04-09T10:14:33Z"
tags: []
categories: ["企业架构"]
slug: "httpclient"
draft: false
lastmod: "2009-04-17T17:28:51Z"
id: 364159
url: "https://mgoann.iteye.com/blog/364159"
---

**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去请求对应的资源。