【问题标题】:Handling Redirect 302 in Java在 Java 中处理重定向 302
【发布时间】:2011-12-28 10:26:35
【问题描述】:

我一直在尝试在 java 代码中处理重定向(302)...而我使用的代码 org.apache.commons.httpclient.HttpClient 没有声明 setRedirectStrategy(),所以我必须编写自己的重定向实现:

private void loadHttp302Request(HttpMethod method, HttpClient client,
            int status, String urlString) throws HttpException, IOException {
        if (status!=302)
            return;
        String[] url = urlString.split("/");
        logger.debug("Method -> loadHttp302Request -> Location : " + method.getResponseHeader("Location")
                .getValue());

        logger.debug("Method -> loadHttp302Request -> Cookies : " + method.getResponseHeader("Set-Cookie")
                .getValue());

        logger.debug("Method -> loadHttp302Request -> Referrer : " + url[0]+"//"+url[2]);

        HttpMethod theMethod = new GetMethod(urlString+method.getResponseHeader("Location")
                .getValue());
        theMethod.setRequestHeader("Cookie", method.getResponseHeader("Set-Cookie")
                .getValue());
        theMethod.setRequestHeader("Referrer",url[0]+"//"+url[2]);
        int _status = client.executeMethod(theMethod);
        logger.debug("Method -> loadHttp302Request -> Status : " + _status);
        method = theMethod;
    }

执行此操作后,状态码等于 200,因此看起来一切正常,但响应正文和响应流均为空。我已经能够用 Wireshark 嗅探 TCP 流,就 Wireshark 而言,我从我的重定向代码中收到了整个响应体......所以我不确定我做错了什么或接下来要寻找什么...理想情况下,如果我可以使用setRedirectStrategy(),那就太好了,但因为它是客户的代码:p 我被困在使用org.apache.commons.httpclient.HttpClient...

我调试了executeMethod(),发现当从输入流中读取响应时,它似乎什么也没收到,尽管wireshark肯定显示我收到了完整的响应正文。

任何想法都将不胜感激:)

【问题讨论】:

  • getMethod urlString 应该换成url[0]+"//"+url[2] 不是吗?
  • Nope... 那么你将有一个路径 = abc.com/www.abc.com

标签: java http redirect


【解决方案1】:

method = theMethod;loadHttp302Request 的末尾不会做任何有用的事情。当loadHttp302Request 返回时,调用(java)方法中的method 对象指针仍将指向原始的HttpMethod 对象。

loadHttp302Request返回theMethod,然后从中获取响应内容。

【讨论】:

  • 感谢您的回答。我从loadHttp302Request 方法返回theMethod,而不是复制theMethod 的内容,我做了以下操作:int status = httpClient.executeMethod(theMethod); HttpMethod requestMethod = loadHttp302Request(theMethod, httpClient, status, urlStr); if (requestMethod != null) { theMethod = requestMethod; } 现在,它正在打开网页,但是当我点击网页中的任何链接时,它会让我返回到我的登录页面。有什么想法吗?
  • 可能您没有正确保留和重新发送会话 cookie。我会先检查一下。
  • 我如何才能保留和重新发送会话 cookie?
  • HttpClient 应该为此提供便利。检查文档或打开一个新的 SO 问题。
  • 请跟进下一个问题,如果你能帮我解决这个问题:stackoverflow.com/questions/8661984/…
猜你喜欢
  • 2021-09-13
  • 2018-04-18
  • 2012-06-25
  • 2020-03-16
  • 2018-07-15
  • 1970-01-01
  • 1970-01-01
  • 2018-09-28
相关资源
最近更新 更多