Tuesday, February 7, 2017

android - HttpURLConnection example

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/coordinator_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#f5f0f0"
    >
    <Button
        android:id="@+id/btn_do"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Do AsyncTask"
        android:layout_margin="25dp"
        android:layout_gravity="top|center_horizontal"
        />
    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_anchor="@id/btn_do"
        android:layout_gravity="bottom"
        app:layout_anchorGravity="bottom"
        android:layout_margin="10dp"
        android:background="#faffff"
        />
</android.support.design.widget.CoordinatorLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

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 MainActivity extends AppCompatActivity {
    private Context mContext;
    private Activity mActivity;

    private CoordinatorLayout mCLayout;
    private Button mButtonDo;
    private ProgressDialog mProgressDialog;
    private TextView mTextView;

    private AsyncTask mMyTask;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the application context
        mContext = getApplicationContext();
        mActivity = MainActivity.this;

        // Get the widget reference from XML layout
        mCLayout = (CoordinatorLayout) findViewById(R.id.coordinator_layout);
        mButtonDo = (Button) findViewById(R.id.btn_do);
        mTextView = (TextView) findViewById(R.id.tv);

        // Enable scrolling
        mTextView.setMovementMethod(new ScrollingMovementMethod());

        // Initialize the progress dialog
        mProgressDialog = new ProgressDialog(mActivity);
        mProgressDialog.setIndeterminate(true);
        // Progress dialog horizontal style
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        // Progress dialog title
        mProgressDialog.setTitle("AsyncTask");
        // Progress dialog message
        mProgressDialog.setMessage("Please wait, we are downloading your file...");

        // Initialize a new click listener for positive button widget
        mButtonDo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Execute the async task
                mMyTask = new DownloadTask()
                        .execute(stringToURL("http://pastebin.com/raw/wgkJgazE"));
            }
        });
    }

    private class DownloadTask extends AsyncTask<URL,Void,String>{
        // Before the tasks execution
        protected void onPreExecute(){
            // Display the progress dialog on async task start
            mProgressDialog.show();
        }

        // Do the task in background/non UI thread
        protected String doInBackground(URL...urls){
            URL url = urls[0];
            /*
                HttpURLConnection
                    A URLConnection with support for HTTP-specific features
            */
            HttpURLConnection connection = null;
            /*
                BufferedReader
                    Reads text from a character-input stream, buffering characters so as to provide
                    for the efficient reading of characters, arrays, and lines.
            */
            BufferedReader bufferedReader = null;

            try{
                // Initialize a new http url connection
                connection = (HttpURLConnection) url.openConnection();

                /*
                openConnection
                    URLConnection openConnection ()

                        Returns a URLConnection instance that represents a connection to the
                        remote object referred to by the URL.
                */
                // Connect the http url connection
                connection.connect();

                /*
                    getInputStream
                        InputStream getInputStream ()

                            Returns an input stream that reads from this open connection.
                            A SocketTimeoutException can be thrown when reading from the returned
                            input stream if the read timeout expires before
                            data is available for read.
                */
                // Get the input stream from http url connection
                InputStream inputStream = connection.getInputStream();

                /*
                    InputStreamReader
                        An InputStreamReader is a bridge from byte streams to character streams: It
                        reads bytes and decodes them into characters using a specified charset. The
                        charset that it uses may be specified by name or may be given explicitly,
                        or the platform's default charset may be accepted.
                */
                // Get the buffered reader from input stream reader
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

                // Initialize a new string buffer object
                StringBuffer stringBuffer = new StringBuffer();

                String line ="";
                // Loop through the lines
                while((line= bufferedReader.readLine())!=null){
                    // Append the current line to string buffer
                    stringBuffer.append(line);

                    // Optionally add a new line to the string buffer
                    //stringBuffer.append("\n");
                }

                // Return the string buffer as string
                return stringBuffer.toString();
            }catch(IOException e){
                e.printStackTrace();
            }finally{
                // Disconnect the http url connection
                connection.disconnect();

                try{
                    // Close the buffered reader
                    bufferedReader.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
            return null;
        }

        // When all async task done
        protected void onPostExecute(String result){
            // Hide the progress dialog
            mProgressDialog.dismiss();

            // Display the downloaded file's text in text view
            mTextView.setText(result);
        }
    }

    // Custom method to convert string to url
    protected URL stringToURL(String urlString){
        try{
            URL url = new URL(urlString);
            return url;
        }catch(MalformedURLException e){
            e.printStackTrace();
        }
        return null;
    }
}
AndroidManifest.xml [permission]

<uses-permission android:name="android.permission.INTERNET" />