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
    }



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章