Opening http connection in android

Android has the package which can be used to access network resources. The base class for HTTP network access in the package is the HttpURLConnection class.

HttpURLConnection class can be used for the following:
1. Obtaining a HttpURLConnection by calling URL.openConnection()
2. Prepare the request.
3. Upload a request body.
4. Read the response. If the response has no body, that method returns an empty stream.
5. Disconnect, after the response has been read, by calling disconnect(). Disconnecting releases the resources held by a connection so they may be closed or reused.

Permissions Required:

android.permission.INTERNET for http connection and android.permission.ACCESS_NETWORK_STATE for checking network status.


Firstly check if network is connected or not by using ConnectivityManager class.NetworkInfo gets an instance that represents the current network connection.

ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting())
Log.i("hi", "connected internet");
} else
Log.i("hi", "not connected to internet");


Opening a Http connection to a url in the following way:

URL url = new URL("");
URLConnection conn = url.openConnection();

Use HttpURLConnection object to connect and get response input stream using
getInputStream() in the following way:

InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection")
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.connect(); response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK)
in = httpConn.getInputStream();
} catch (Exception ex) {
Toast.makeText(this, "Error in connecting to the server", Toast.LENGTH_LONG).show();
throw new IOException("Error connecting");

Lets say that the response is a image ,then we can decode the input stream into a bitmap in the following way.
bitmap = BitmapFactory.decodeStream(in);
The response can a be a image or a string ,depending upon the type of response we can decode the stream.

Related Post:

Check internet connection status in android


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s