当我调用 connect() 时,Java HttpURLConnection 无法连接
-
23-09-2019 - |
题
我正在尝试编写一个程序来对我的网络应用程序进行自动化测试。为了实现此目的,我使用 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() 来更改 switch out the 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()
),用于将被返回并处理该响应。
其他提示
添加以下你的onCreate
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
你为什么不使用 HttpClient的 Apache的。
尝试 setFollowRedirects ,因为它可能会有所帮助。其实,看看试试getFollowRedirects
如果是这个问题,首先(不可能的,因为它是真实的默认情况下)。
修改:如果这不是你的问题,我会尝试从连接读的东西(如你getResponseCode
做,但我会尝试也getHeaderField
,看是否读取所有东西导致重定向到尊重)。
不隶属于 StackOverflow