0

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.

  • Have you added the [INTERNET](http://developer.android.com/reference/android/Manifest.permission.html#INTERNET) permission to your manifest? – Sander van't Veer Apr 16 '14 at 11:32

2 Answers2

0

Add below permissions in manifest file-

 <uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
yuva ツ
  • 3,707
  • 9
  • 50
  • 78
0

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!

kodartcha
  • 1,063
  • 12
  • 23