我正在尝试编写一个程序来对我的 webapp 进行自动化测试。为此,我使用 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());
为什么我会看到这种行为?我做错什么了吗?
谢谢您的帮助。