当我调用 connect() 时,Java HttpURLConnection 没有连接

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

I'm trying to write a program to do automated testing on my webapp. To accomplish this, I open up a connection using HttpURLConnection.

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

One of the pages that I'm trying to test performs a 302 redirect. My test code looks like this :

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,对?

So, let's say that urlToSend is http://www.foo.com/bar.jsp, and that this page redirects you to http://www.foo.com/quux.jsp. My println statement should print out http://www.foo.com/quux.jsp, right?

错了.

重定向永远不会发生,它会打印出原始 URL.但是,如果我通过调用 connection.getResponseCode() 来切换掉 connection.connect() 行,它会神奇地起作用.

The redirect never happens, and it prints out the original URL. However, if I change switch out the connection.connect() line with a call to connection.getResponseCode(), it magically works.

URL currentUrl = new URL(urlToSend);
HttpURLConnection connection = (HttpURLConnection) currentUrl.openConnection();
//connection.connect();
connection.getResponseCode();
system.out.println(connection.getURL().toString());

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

Why am I seeing this behavior? Am I doing anything wrong?

感谢您的帮助.

推荐答案

connect() 方法只是创建一个连接.您必须提交请求(通过调用 getInputStream()getResponseCode()getResponseMessage())才能返回响应并已处理.

The connect() method just creates a connection. You have to commit the request (by calling getInputStream(), getResponseCode(), or getResponseMessage()) for the response to be returned and processed.

相关文章