Android HttpURLConnection Example

This article will tell you how to use java.net.HttpURLConnection class to send an http request and get an http server response in the android application.

1. HttpURLConnection use steps.

  1. Create a URL instance.
    URL url = new URL("http://www.yahoo.com");
  2. Open url connection and cast it to HttpURLConnection.
    HttpURLConnection httpConn = (HttpURLConnection)url.openConnection();
  3. Set request method. The request method can be GET, POST, DELETE, etc. Request method must be uppercase, otherwise below exception will be thrown. java.net.ProtocolException: Expected one of [OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, PATCH] but was get
    httpConn.setRequestMethod("GET");
  4. If the request method is GET, then use the below code to open the input stream and read server response data.
    InputStream inputStream = httpConn.getInputStream();
    InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
    String line = bufferedReader.readLine();
  5. For the POST request method, use the below code to open the output stream to the server url and write post data to it. After posting, open the input stream again to get the server response.
    OutputStream outputStream = httpConn.getOutputStream();
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
    BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
    bufferedWriter.write("user=jerry&pasword=666666");
  6. After using HttpURLConnection, do not forget close the related reader or writer and call HttpURLConnection‘s disconnect() method to close the connection to release network resources.
    httpConn.disconnect();

2. HttpURLConnection Examples.

  1. In this example, the read server response process occurs in a child thread. The child thread sends a message to the activity main thread’s Handler object to update the response data in TextView.
  2. This is because the child thread can not update UI controls in activity directly, otherwise, an error will happen.
  3. Below is this example demo video ( android httpurlconnection example ).

2.1 Main Activity.

  1. HttpURLConnectionActivity.java.
    package com.dev2qa.example.network;
    
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.support.v7.app.AppCompatActivity;
    import android.text.TextUtils;
    import android.util.Log;
    import android.view.View;
    import android.webkit.URLUtil;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;
    
    import com.dev2qa.example.R;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    
    public class HttpURLConnectionActivity extends AppCompatActivity {
    
        // Debug log tag.
        private static final String TAG_HTTP_URL_CONNECTION = "HTTP_URL_CONNECTION";
    
        // Child thread sent message type value to activity main thread Handler.
        private static final int REQUEST_CODE_SHOW_RESPONSE_TEXT = 1;
    
        // The key of message stored server returned data.
        private static final String KEY_RESPONSE_TEXT = "KEY_RESPONSE_TEXT";
    
        // Request method GET. The value must be uppercase.
        private static final String REQUEST_METHOD_GET = "GET";
    
        // Request web page url input text box.
        private EditText requestUrlEditor = null;
    
        // Send http request button.
        private Button requestUrlButton = null;
    
        // TextView to display server returned page html text.
        private TextView responseTextView = null;
    
        // This handler used to listen to child thread show return page html text message and display those text in responseTextView.
        private Handler uiUpdater = null;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_http_url_connection);
    
            setTitle("dev2qa.com - HttpURLConnection Example");
    
            // Init app ui controls.
            initControls();
    
            // When click request url button.
            requestUrlButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String reqUrl =  requestUrlEditor.getText().toString();
                    if(!TextUtils.isEmpty(reqUrl))
                    {
                        if(URLUtil.isHttpUrl(reqUrl) || URLUtil.isHttpsUrl(reqUrl))
                        {
                            startSendHttpRequestThread(reqUrl);
                        }else
                        {
                            Toast.makeText(getApplicationContext(), "The request url is not a valid http or https url.", Toast.LENGTH_LONG).show();
                        }
                    }else
                    {
                        Toast.makeText(getApplicationContext(), "The request url can not be empty.", Toast.LENGTH_LONG).show();
                    }
                }
            });
    
        }
    
        // Initialize app controls.
        private void initControls()
        {
            if(requestUrlEditor == null)
            {
                requestUrlEditor = (EditText)findViewById(R.id.http_url_editor);
            }
    
            if(requestUrlButton == null)
            {
                requestUrlButton = (Button)findViewById(R.id.http_url_request_button);
            }
    
            if(responseTextView == null)
            {
                responseTextView = (TextView)findViewById(R.id.http_url_response_text_view);
            }
    
            // This handler is used to wait for child thread message to update server response text in TextView.
            if(uiUpdater == null)
            {
                uiUpdater = new Handler()
                {
                    @Override
                    public void handleMessage(Message msg) {
                        if(msg.what == REQUEST_CODE_SHOW_RESPONSE_TEXT)
                        {
                            Bundle bundle = msg.getData();
                            if(bundle != null)
                            {
                                String responseText = bundle.getString(KEY_RESPONSE_TEXT);
                                responseTextView.setText(responseText);
                            }
                        }
                    }
                };
            }
        }
    
        /* Start a thread to send http request to web server use HttpURLConnection object. */
        private void startSendHttpRequestThread(final String reqUrl)
        {
            Thread sendHttpRequestThread = new Thread()
            {
                @Override
                public void run() {
                    // Maintain http url connection.
                    HttpURLConnection httpConn = null;
    
                    // Read text input stream.
                    InputStreamReader isReader = null;
    
                    // Read text into buffer.
                    BufferedReader bufReader = null;
    
                    // Save server response text.
                    StringBuffer readTextBuf = new StringBuffer();
    
                    try {
                        // Create a URL object use page url.
                        URL url = new URL(reqUrl);
    
                        // Open http connection to web server.
                        httpConn = (HttpURLConnection)url.openConnection();
    
                        // Set http request method to get.
                        httpConn.setRequestMethod(REQUEST_METHOD_GET);
    
                        // Set connection timeout and read timeout value.
                        httpConn.setConnectTimeout(10000);
                        httpConn.setReadTimeout(10000);
    
                        // Get input stream from web url connection.
                        InputStream inputStream = httpConn.getInputStream();
    
                        // Create input stream reader based on url connection input stream.
                        isReader = new InputStreamReader(inputStream);
    
                        // Create buffered reader.
                        bufReader = new BufferedReader(isReader);
    
                        // Read line of text from server response.
                        String line = bufReader.readLine();
    
                        // Loop while return line is not null.
                        while(line != null)
                        {
                            // Append the text to string buffer.
                            readTextBuf.append(line);
    
                            // Continue to read text line.
                            line = bufReader.readLine();
                        }
    
                        // Send message to main thread to update response text in TextView after read all.
                        Message message = new Message();
    
                        // Set message type.
                        message.what = REQUEST_CODE_SHOW_RESPONSE_TEXT;
    
                        // Create a bundle object.
                        Bundle bundle = new Bundle();
                        // Put response text in the bundle with the special key.
                        bundle.putString(KEY_RESPONSE_TEXT, readTextBuf.toString());
                        // Set bundle data in message.
                        message.setData(bundle);
                        // Send message to main thread Handler to process.
                        uiUpdater.sendMessage(message);
                    }catch(MalformedURLException ex)
                    {
                        Log.e(TAG_HTTP_URL_CONNECTION, ex.getMessage(), ex);
                    }catch(IOException ex)
                    {
                        Log.e(TAG_HTTP_URL_CONNECTION, ex.getMessage(), ex);
                    }finally {
                        try {
                            if (bufReader != null) {
                                bufReader.close();
                                bufReader = null;
                            }
    
                            if (isReader != null) {
                                isReader.close();
                                isReader = null;
                            }
    
                            if (httpConn != null) {
                                httpConn.disconnect();
                                httpConn = null;
                            }
                        }catch (IOException ex)
                        {
                            Log.e(TAG_HTTP_URL_CONNECTION, ex.getMessage(), ex);
                        }
                    }
                }
            };
            // Start the child thread to request web page.
            sendHttpRequestThread.start();
        }
    }

2.2 Main Layout XML File.

  1. activity_http_url_connection.xml
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
    
            <EditText
                android:id="@+id/http_url_editor"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:hint="Input a web page url to get."
                android:layout_weight="1"/>
    
            <Button
                android:id="@+id/http_url_request_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Request Page"/>
        </LinearLayout>
    
        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            
            <TextView
                android:id="@+id/http_url_response_text_view"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
            
        </ScrollView>
    
    </LinearLayout>

2.3 Android Manifest Xml File.

  1. Because this example will connect network resources, so you need to declare the below permission in the android manifest XML file.
  2. AndroidManifest.xml.
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.dev2qa.example">
    
        <!-- Example required permission. -->
        <uses-permission android:name="android.permission.INTERNET" />
    
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            
            <activity android:name=".network.HttpURLConnectionActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
    
    </manifest>

7 thoughts on “Android HttpURLConnection Example”

  1. Quality content is the key to interest the users to go to see the web page, that’s what this web site is providing.

  2. Hi, this article is useful in 2019 lol. How do I only return a server response status. Thank you

  3. Nice !
    I have followed many examples without luck
    You made my day

    But, would you like to show me how to track whether success or failure ?
    In my case I need to know the status

  4. Hi. I’m working on a android app that will display the position of the baby inside a crib using a beam sensors connected to RPI3.

    I created a webserver on RPI3 that displays the position of the baby. I just want to know how I can get the web running on my application to see the position of the baby. Thank you

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.