Java中的非重定向HttpURLConnection请求没有答案

时间:2015-01-06 03:40:52

标签: java url redirect httprequest httpurlconnection

这是我尝试做的最小例子:

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();时,是否有人为什么没有显示任何内容的线索?

1 个答案:

答案 0 :(得分:1)

很明显为什么你没有得到响应字符串。您已禁用以自动关注重定向。所以你可能会得到一个只包含标题,没有正文的响应。您的响应字符串正在收集正文的字节,因为响应中没有正文只是说“转到另一个位置”,所以您的字符串为空。

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

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