Android | Connecting to the Network Using HttpUrlConnection

Datetime:2016-08-22 23:22:52          Topic: Andrew Development           Share

One common task for most Android apps is connecting to the Internet. Most network-connected Android apps use HTTP to send and receive data. This article shows you how to write a simple application that connects to the Internet, send HTTP GET request & display the response.

Objectives

  • How to send HTTP GET request to a web server and display the response?
  • How to check network connection?
  • How to use AsyncTask to perform network operations on a separate thread?

Environment & Tools

Tools used in this post

About this Sample App

We will build an app that send HTTP GET request and display the response.

( 1 ) Create new Android Project

  • Application Name: android-http
  • Package Name: com.hmkcode.android.http
  • Minimum SDK: API 8: Android 2.2 (Froyo)

( 2 ) Add Permissions

  • Add the following two lines to the AndroidMainifest.xml file
<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

( 2 ) Design App Layout

  • Add two TextView to activity_main.xml .
  • First TextView for displaying network connection info.
  • Second TextView to display message from server.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.hmkcode.android.http.MainActivity">



    <TextView
        android:id="@+id/tvIsConnected"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:background="#FF0000"
        android:textColor="#FFF"
        android:textSize="18dp"
        android:padding="5dp"
        android:layout_marginBottom="5dp"
        android:text="is connected? " />

    <TextView
        android:id="@+id/tvResult"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:background="#ffffff"
        android:textColor="#000"
        android:textSize="18dp"
        android:padding="5dp"
        android:layout_marginBottom="5dp"
        android:text="" />
</LinearLayout>

( 3 ) Check the Network Connection

  • Before making any network operation you need to check if you are connected or not.
  • To check whether a network connection is available use getActiveNetworkInfo() and isConnected() .
public boolean checkNetworkConnection() {
        ConnectivityManager connMgr = (ConnectivityManager)
                getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        boolean isConnected = false;
        if (networkInfo != null && (isConnected = networkInfo.isConnected())) {
            // show "Connected" & type of network "WIFI or MOBILE"
            tvIsConnected.setText("Connected "+networkInfo.getTypeName());
            // change background color to red
            tvIsConnected.setBackgroundColor(0xFF7CCC26);


        } else {
            // show "Not Connected"
            tvIsConnected.setText("Not Connected");
            // change background color to green
            tvIsConnected.setBackgroundColor(0xFFFF0000);
        }

        return isConnected;
    }

( 4 ) Perform HTTP GET Request

  • The simplest example for network operation is HTTP GET request.
  • We create a new URL object by passing url string to the constructor.
  • The URL object is used to establish an HttpURLConnection .
  • Then, we execute the operation and receive the response as InputStream .
  • Finally, we use helper method to convert InputStream to string.
private String HttpGet(String myUrl) throws IOException {
      InputStream inputStream = null;
      String result = "";

          URL url = new URL(myUrl);

          // create HttpURLConnection
          HttpURLConnection conn = (HttpURLConnection) url.openConnection();

          // make GET request to the given URL
          conn.connect();

          // receive response as inputStream
          inputStream = conn.getInputStream();

          // convert inputstream to string
          if(inputStream != null)
              result = convertInputStreamToString(inputStream);
          else
              result = "Did not work!";

      return result;
  }

( 5 ) Perform Network Operations on a Separate Thread

  • Network operation should always run on a seperate thread to avoid UI freeze.
  • The AsyncTask class provides one of the simplest ways to create separate thread from the UI thread.
  • Create an inner class extending AsyncTask .
  • Override doInBackground() & onPostExecute .
private class HTTPAsyncTask extends AsyncTask<String, Void, String> {
      @Override
      protected String doInBackground(String... urls) {

          // params comes from the execute() call: params[0] is the url.
          try {
              return HttpGet(urls[0]);
          } catch (IOException e) {
              return "Unable to retrieve web page. URL may be invalid.";
          }
      }
      // onPostExecute displays the results of the AsyncTask.
      @Override
      protected void onPostExecute(String result) {
          tvResult.setText(result);
      }
  }

( 6 ) Convert the InputStream to a String

  • We will use a helper method to convert InputStream byte into String
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
          BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
          String line = "";
          String result = "";
          while((line = bufferedReader.readLine()) != null)
              result += line;

          inputStream.close();
          return result;

      }

Source Code @ GitHub





About List