当我调用connect()时,Java HttpURLConnection无法连接

san*_*oid 7 java connection url httpurlconnection http-status-code-302

我正在尝试编写一个程序来对我的webapp进行自动化测试.为此,我使用HttpURLConnection打开连接.

我正在尝试测试的其中一个页面执行302重定向.我的测试代码如下所示:

URL currentUrl = new URL(urlToSend);
HttpURLConnection connection = (HttpURLConnection) currentUrl.openConnection();
connection.connect();
system.out.println(connection.getURL().toString());
Run Code Online (Sandbox Code Playgroud)

所以,假设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());
Run Code Online (Sandbox Code Playgroud)

为什么我看到这种行为?我做错了吗?

谢谢您的帮助.

eri*_*son 17

connect()方法只是创建一个连接.你必须提交请求(通过调用getInputStream(),getResponseCode()getResponseMessage()),用于将被返回并处理该响应.

  • 这次真是万分感谢!一直试图理解为什么人们在不调用 connect() 的情况下发出 getInputStream() 等。你刚刚向我澄清了这一点。 (2认同)