假如我们有三个url如下:
A: http://www.domain1.com
B: http://www.domain2.com
C: http://www.domain2.com/test
其中B和C的host是一样的
我们通过httpclient请求A,A需要重写向到B,但B又需要重定向到C,这个时候就会出现CircularRedirectException的异常
HttpClient httpClient = new HttpClient();
GetMethod get = new GetMethod(url);
try {
httpClient.executeMethod(get);
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}查看httpclient中如下:HttpMethodDirector类中的processRedirectResponse方法
if (this.redirectLocations.contains(redirectUri)) {
throw new CircularRedirectException("Circular redirect to '" +
redirectUri + "'");
}httpclient在每次处理请求时都会将请求的url加入redirectLocations, 并在每次请求当前url将,判断该url是否在redirectLocations当中,如果在里面,则抛出异常
如果想去掉该限制,可以设置method的followRedirects属性为false,httpclient如下:
GetMethod的followRedirects属性默认为true
public GetMethod() {
setFollowRedirects(true);
}
/**
* Constructor specifying a URI.
*
* @param uri either an absolute or relative URI
*
* @since 1.0
*/
public GetMethod(String uri) {
super(uri);
LOG.trace("enter GetMethod(String)");
setFollowRedirects(true);
} private boolean isRedirectNeeded(final HttpMethod method) {
switch (method.getStatusCode()) {
case HttpStatus.SC_MOVED_TEMPORARILY:
case HttpStatus.SC_MOVED_PERMANENTLY:
case HttpStatus.SC_SEE_OTHER:
case HttpStatus.SC_TEMPORARY_REDIRECT:
LOG.debug("Redirect required");
if (method.getFollowRedirects()) {
return true;
} else {
return false;
}
default:
return false;
} //end of switch
}
本文介绍使用HttpClient时遇到CircularRedirectException的原因及解决方法。当请求经过多次重定向形成循环时,HttpClient会抛出此异常。文章提供了禁用自动重定向功能的具体步骤。
2621

被折叠的 条评论
为什么被折叠?



