我试图编写一个程序在我的webapp上执行自动测试。为了做到这一点,我使用HttpURLConnection打开了一个连接。当我调用connect时,HttpURLConnection没有连接()
我试图测试的一个页面执行302重定向。我的测试代码如下所示:
URL currentUrl = new URL(urlToSend);
HttpURLConnection connection = (HttpURLConnection) currentUrl.openConnection();
connection.connect();
system.out.println(connection.getURL().toString());
所以,让我们说,urlToSend是http://www.foo.com/bar.jsp,而这个页面重定向到http://www.foo.com/quux.jsp。我的println声明应该打印出http://www.foo.com/quux.jsp,对不对?
错误。
重定向从不发生,它打印出原始URL。但是,如果我通过调用connection.getResponseCode()将connection.connect()行切换出来,它神奇地工作。
URL currentUrl = new URL(urlToSend);
HttpURLConnection connection = (HttpURLConnection) currentUrl.openConnection();
//connection.connect();
connection.getResponseCode();
system.out.println(connection.getURL().toString());
为什么我看到这种行为?我做错了什么?
感谢您的帮助。
谢谢,这似乎确实如此! – sangfroid 2010-01-28 00:33:52
谢谢你!一直试图理解为什么人们发出getInputStream()等没有调用connect()。你刚刚向我澄清。 – Renatinn 2015-09-06 20:38:34