Java HttpURLConnection不连接时,我调用connect() [英] Java HttpURLConnection doesn't connect when I call connect()

查看:971
本文介绍了Java HttpURLConnection不连接时,我调用connect()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个程序,在我的webapp上进行自动测试。为了实现这一点,我使用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。但是,如果我改变开关connect.connect()线调用connection.getResponseCode(),它奇迹般工作。

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

为什么会出现这种情况?我会做错什么?



感谢您的帮助。

解决方案

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


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

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());

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?

WRONG.

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?

Thanks for the help.

解决方案

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.

这篇关于Java HttpURLConnection不连接时,我调用connect()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆