Java HttpURLConnection doesn#39;t connect when I call connect()(当我调用 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.
这篇关于当我调用 connect() 时,Java HttpURLConnection 没有连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:当我调用 connect() 时,Java HttpURLConnection 没有连接
基础教程推荐
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01