Java HttpURLConnection doesn't connect when I

2020-01-31 03:47发布

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.

5条回答
该账号已被封号
2楼-- · 2020-01-31 04:17

Why don't you use HttpClient from apache.

查看更多
聊天终结者
3楼-- · 2020-01-31 04:27

Add the following in your onCreate

StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy); 
查看更多
叛逆
4楼-- · 2020-01-31 04:38

Try setFollowRedirects, as it might help. Actually, try getFollowRedirects to see if it's the problem, first (unlikely since it's true by default).

Edit: If this is not your problem, I would try reading something from the connection (as you do with getResponseCode but I would try also getHeaderField to see if reading anything at all causes the redirect to be respected).

查看更多
Deceive 欺骗
5楼-- · 2020-01-31 04:41

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.

查看更多
smile是对你的礼貌
6楼-- · 2020-01-31 04:41

The connect() method is implemented in the URLConnection class, and is not overridden by the HttpURLConnection class.

The URLConnection class is not aware of HTTP, and so should not follow the HTTP redirect even if it was creating a real connection.

If you want behaviour intrinsic to the HTTP protocol, you probably want to stick to methods implemented in the HttpURLConnection class, as the getResponseCode() method is.

查看更多
登录 后发表回答