httpclient中出现CircularRedirectException异常分析

假如我们有三个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
    }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值