HTTP组件核心跟随重定向

7

我正在尝试寻找一种让http组件跟随重定向的方法,但在谷歌上没有找到任何信息,因此我来这里寻求帮助。

该函数:

public String GetSite(String site, String path) throws Exception {

    HttpParams params = new SyncBasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
    HttpProtocolParams.setUseExpectContinue(params, true);

    HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[]{
                // Required protocol interceptors
                new RequestContent(),
                new RequestTargetHost(),
                // Recommended protocol interceptors
                new RequestConnControl(),
                new RequestUserAgent(),
                new RequestExpectContinue()});

    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

    HttpContext context = new BasicHttpContext(null);
    HttpHost host = new HttpHost(site, 80);

    DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
    ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();

    context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

    try {

        String[] targets = {
            path};

        for (int i = 0; i < targets.length; i++) {
            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket, params);
            }
            BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]);
            request.setParams(params);
            httpexecutor.preProcess(request, httpproc, context);
            HttpResponse response = httpexecutor.execute(request, conn, context);
            response.setParams(params);
            httpexecutor.postProcess(response, httpproc, context);

            if (!connStrategy.keepAlive(response, context)) {
                conn.close();
            } else {
            }
            return (EntityUtils.toString(response.getEntity()));

        }
    } finally {
        conn.close();
    }
    return null;

}

这个也需要帮忙吗?因为我找不到任何相关的内容...


你确定你真的需要这么复杂的代码吗?http://hc.apache.org/httpcomponents-client-ga/examples.html通常都可以胜任。第一个(响应处理)示例按默认方式跟随重定向。 - palacsint
已经通过使用URL连接器解决了它。 - Cakestep
在这种情况下,您应该创建一个新答案并接受它。这样我就可以帮助其他遇到同样问题的人,而其他人也不会再次为您解决此问题。 - palacsint
2
Cakestep,请您可以发一下您的解决方案吗?我也遇到了同样的问题。 - Urban
你是否处于特定的Android上下文环境中? - Yves Martin
1个回答

2

我建议您使用基本的DefaultHttpClient,它支持重定向而无需任何调整或额外代码。其行为可以通过4个参数来控制,这些参数在第5.2节HttpClient参数中描述

如果您真的不想依赖于httpcomponents-client,而只想依赖于httpcomponents-core,那么您将需要选择org.apache.http.impl.client.RedirectStrategy的实现,并创建自己的代码来解析响应,确定是否是有效的重定向(仔细阅读HTTP规范,这并不简单),并在需要时循环触发新请求。

我的意见是:没有理由再编写如此复杂的代码,有一天可能还需要验证,并且您还需要添加对此的支持。因此,请依赖于HttpClient。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接