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

一笑奈何 提交于 2019-11-27 21:37:43

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.

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.

Add the following in your onCreate

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

Why don't you use HttpClient from apache.

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

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