5 Apr 2016

GET/POST request Using HttpURLConnection.

Hi All,

Today I am sharing one of the important code snippet. As we all know  org.apache.http.client.HttpClient,

This interface was deprecated in API level 22. So now onward need to use URLConnection instead.
Means that you should switch to java.net.URL.openConnection().

Here is the http utility class to send GET/POST request to the server.

RestClient :
package com.httpurlconnection;

import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class RestClient
{
    public enum RequestMethod
    {
        GET,
        POST
    }

    private HashMap<String, String> params;

    private HashMap<String, String> headers;

    private String serviceUrl;

    private int responseCode;

    private String message;

    private String response;

    private InputStream inputStream = null;

    private HttpURLConnection urlConnection = null;

    private String strJson=null;

    public RestClient( String url )
    {
        this.serviceUrl = url;
        params = new HashMap<String, String>();
        headers = new HashMap<String, String>();
    }

    public String getResponse()
    {
        return response;
    }

    public String getErrorMessage()
    {
        return message;
    }

    public int getResponseCode()
    {
        return responseCode;
    }


    public void AddParam( String name, String value )
    {
        params.put(name, value);
    }

    public void AddHeader( String name, String value )
    {
        headers.put(name, value);
    }

    public void AddData( String strJson )
    {
        this.strJson=strJson;
    }

    public void Execute( RequestMethod method ) throws Exception
    {
        switch ( method )
        {
            case GET:
            {
                //add parameters
                String combinedParams = "";
                if ( !params.isEmpty() )
                {
                    combinedParams += "?";
                    for ( Map.Entry<String, String> p : params.entrySet() )
                    {
                        String paramString = URLEncoder.encode(p.getKey(), "UTF-8") + "=" + URLEncoder.encode(p.getValue(), "UTF-8");
                        if ( combinedParams.length() > 1 )
                        {
                            combinedParams += "&" + paramString;
                        }
                        else
                        {
                            combinedParams += paramString;
                        }
                    }
                }
                try
                {
                    URL url = new URL(serviceUrl + combinedParams);

                    urlConnection = (HttpURLConnection) url.openConnection();
                    urlConnection.setRequestMethod("GET");
                    urlConnection.setReadTimeout(15000);
                    urlConnection.setConnectTimeout(15000);

                    /* Add header */
                    if ( !headers.isEmpty() )
                    {
                        for ( Map.Entry<String, String> header : headers.entrySet() )
                        {
                            urlConnection.setRequestProperty(header.getKey(), header.getValue());
                        }
                    }

                    int statusCode = urlConnection.getResponseCode();

                /* 200 represents HTTP OK */
                    if ( statusCode == HttpURLConnection.HTTP_OK )
                    {
                        inputStream = new BufferedInputStream(urlConnection.getInputStream());
                        response = convertStreamToString(inputStream);
                        Log.e("Response ::", response);
                    }
                }
                catch ( Exception e )
                {
                    Log.d("Exception::", e.getLocalizedMessage());
                }
                finally
                {
                    urlConnection.disconnect();
                }
                break;
            }
            case POST:
            {
                try
                {
                    URL url = new URL(serviceUrl);

                    urlConnection = (HttpURLConnection) url.openConnection();
                    urlConnection.setRequestMethod("POST");
                    urlConnection.setReadTimeout(15000);
                    urlConnection.setConnectTimeout(15000);
                    urlConnection.setDoInput(true);// true indicates the server returns response
                    urlConnection.setDoOutput(true);// true indicates POST request

                 /* Add header */
                    if ( !headers.isEmpty())
                    {
                        for ( Map.Entry<String, String> header : headers.entrySet() )
                        {
                            urlConnection.setRequestProperty(header.getKey(), header.getValue());
                        }
                    }
                    /* Parameter */
                    if(!params.isEmpty())
                    {
                        OutputStream os = urlConnection.getOutputStream();
                        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
                        writer.write(getPostDataString(params));

                        writer.flush();
                        writer.close();
                        os.close();
                    }
                    /* Request with JSON string */
                    if(strJson!=null)
                    {
                        OutputStreamWriter wr= new OutputStreamWriter(urlConnection.getOutputStream());
                        wr.write(strJson);

                    }
                    int statusCode = urlConnection.getResponseCode();

                /* 200 represents HTTP OK */
                    if ( statusCode == HttpURLConnection.HTTP_OK )
                    {
                        inputStream = new BufferedInputStream(urlConnection.getInputStream());
                        response = convertStreamToString(inputStream);
                        Log.e("Response ::", response);
                    }

                }
                catch ( Exception e )
                {
                    Log.d("Exception::", e.getLocalizedMessage());
                }

                finally
                {
                    urlConnection.disconnect();
                }
                break;
            }
        }
    }

    private static String convertStreamToString( InputStream is )
    {

        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();

        String line;
        try {

            br = new BufferedReader(new InputStreamReader(is));
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return sb.toString();
    }

    private String getPostDataString( HashMap<String, String> params ) throws UnsupportedEncodingException
    {
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for ( Map.Entry<String, String> entry : params.entrySet() )
        {
            if ( first )
            {
                first = false;
            }
            else
            {
                result.append("&");
            }

            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }

        return result.toString();
    }
}
How to Use:
 package com.httpurlconnection;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

public class MainActivity extends AppCompatActivity
{
    private static final String TAG = "Http Connection";

    private String url = "Service Url";

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

        new AsyncHttpTask().execute(url);
    }

    public class AsyncHttpTask extends AsyncTask<String, Void, String>
    {
        String response=null;
        @Override
        protected String doInBackground( String... params )
        {
            try
            {
                RestClient client = new RestClient(url);
//                client.AddParam("service", "analytics");
                client.AddHeader("Content-Type", "application/json");
                try
                {
                    client.Execute(RestClient.RequestMethod.GET);
                    response = client.getResponse();
                }
                catch ( Exception e )
                {
                    e.printStackTrace();
                }
            }
            catch ( Exception e )
            {
                Log.d(TAG, e.getLocalizedMessage());
            }
            return response;
        }


        @Override
        protected void onPostExecute( String result )
        {
            /* Download complete. Lets update UI */
            if ( result!=null && result.length()>0)
            {
                Log.e("Response ====",result);
            }
            else
            {
                Log.e(TAG, "Failed to fetch data!");
            }
        }
    }

}
 
I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)

No comments:

Post a Comment