【问题标题】:no answers from a non-redirectional HttpURLConnection request in JavaJava 中的非重定向 HttpURLConnection 请求没有答案
【发布时间】:2015-01-06 03:40:51
【问题描述】:

这是我尝试做的一个最小示例:

public static String fetch () {

    // get a connection to the website
    HttpURLConnection connection = (HttpURLConnection)(new URL("http://example.com?param=ok").openConnection());

    // configure the connection
    connection.setRequestMethod("GET");
    connection.setInstanceFollowRedirects(false);


    connection.setUseCaches(false);
    connection.setDoInput(true);
    connection.setDoOutput(true);

    // send the request
    DataOutputStream ostream = new DataOutputStream(connection.getOutputStream());
    ostream.flush();
    ostream.close();


    // receives the response
    InputStream istream = connection.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(istream));
    StringBuffer response = new StringBuffer();

    String line;
    while ((line = reader.readLine()) != null) {
        response.append(line);
        response.append('\r');
    }
    reader.close();

    return response.toString();
}

为了到达“http://example.com”,服务器首先发送一个重定向,HttpURLConnection自动使用这个重定向,然后显示这个最终死页的响应。 我想得到这个中间响应的字节码。 为此,我尝试使用 setInstanceFollowRedirects 方法并将其设置为 false(参见代码)。它似乎可以工作,因为不再有输出,但这就是我在这里发帖的原因,因为不再有输出了 fuuuu

当我尝试输出return response.toString(); 时,为什么没有显示任何内容?

【问题讨论】:

标签: java url redirect httprequest httpurlconnection


【解决方案1】:

很清楚为什么您没有收到响应字符串。您禁用自动跟踪重定向。所以你可能会得到一个只包含标题,没有正文的响应。您的响应字符串正在收集正文的字节,并且由于响应中没有正文只说“转到另一个位置”,因此您的字符串为空。

您应该执行connection.getResponseCode 并阅读Location 标头以了解下一步该去哪里。然后您可以使用这个新位置创建另一个请求,您将获得“真实”响应。

我不知道“中间响应的字节码”到底是什么意思。我想您对标头值感兴趣。您可以使用connection.getHeaderFields() 获取所有标题。您迭代此映射并收集所有有趣的标头值以进行进一步处理。

【讨论】:

  • 有时我会为自己的愚蠢程度感到惊讶,这太明显了,谢谢先生。
  • 不客气。这不就是我们觉得愚蠢的日常生活吗? :-)
猜你喜欢
  • 2022-09-27
  • 2012-12-24
  • 1970-01-01
  • 2019-03-22
  • 1970-01-01
  • 1970-01-01
  • 2014-11-17
  • 1970-01-01
  • 2017-01-23
相关资源
最近更新 更多