can't connect to internet in ONLY in my android app. Each method to connect internet returns null

…衆ロ難τιáo~ 提交于 2019-12-11 21:31:50

问题


I am using HttpURLConnection's connect method but it returns null. no other message no printstack just null.

URL url = new URL("http://whatever");
URLConnection urlConnection = url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());

In above also it returns the null

Don't know why this comes. But I cant connect to net.

i also tried with HttpURLConnection and urlconnection both are different example.


回答1:


Add below permissions in manifest file-

 <uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />



回答2:


You said you are using HttpURLConnection but in the code you poste URLConnection. This is how you make a proper HttpURLConnection:

URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
  InputStream in = new BufferedInputStream(urlConnection.getInputStream());
  readStream(in);
 finally {
  urlConnection.disconnect();
 }
}

You also have to do this connection outside the main thread (Using AsyncTask or other method) or otherwise the app will crash.

Also add the right permissions for it:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Hope it helps! Good Luck!



来源:https://stackoverflow.com/questions/23108206/cant-connect-to-internet-in-only-in-my-android-app-each-method-to-connect-inte

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