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

标签 java url connection http-status-code-302 httpurlconnection

我正在尝试编写一个程序来对我的网络应用程序进行自动化测试。为此,我使用 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());

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

感谢您的帮助。

最佳答案

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

关于当我调用 connect() 时,Java HttpURLConnection 没有连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2151359/

相关文章:

java - 如何使用 Apache Felix 在 OSGi 中实现 AOP

java - 关于 Java 中的 clone() 、对象类和 Cloneable 接口(interface)的混淆

Web 应用程序中的 Java 类和实例变量内存使用情况?

java - Eclipse Luna 因 JVM 终止而崩溃。退出代码=1

html - 我应该将网站的所有网址重定向到 https 吗?

android - 无法得到 smack 的响应

android - 从带有阿拉伯字符的 url 加载图像

jquery - 在 url 中传递多个类似哈希的参数

java - 连接池

android - 如何像 Whatsapp 和 Viber 一样在电话簿/联系人中添加我的应用程序连接?