Opening http connection in android

Android has the java.net package which can be used to access network resources. The base class for HTTP network access in the java.net 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.

STEP 1:

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");

STEP 2:

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

URL url = new URL("http://www.blograchita.wordpress.com");
URLConnection conn = url.openConnection();

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

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.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect(); response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK)
{
in = httpConn.getInputStream();
in.close();
}
} 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

Advertisements