Java HttpURLConnection doesn't connect when I call connect()

倖福魔咒の 提交于 2019-11-26 20:47:50

问题


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.


回答1:


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.




回答2:


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.




回答3:


Add the following in your onCreate

StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy); 



回答4:


Why don't you use HttpClient from apache.




回答5:


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).



来源:https://stackoverflow.com/questions/2151359/java-httpurlconnection-doesnt-connect-when-i-call-connect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!