问题
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