【发布时间】: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(); 时,为什么没有显示任何内容?
【问题讨论】:
-
这可能会帮助您stackoverflow.com/questions/2793150/…link BTW 我从您的示例中删除了 ?param=OK 并且它运行良好。
标签: java url redirect httprequest httpurlconnection