Showing posts with label network android. Show all posts
Showing posts with label network android. Show all posts

Friday, 27 November 2015

Android HttpURLConnection code for GET and POST Methods



package com.infodat.selltis2;

import android.util.Log;

import com.infodat.selltis2.utils.Constants;
import com.infodat.selltis2.utils.Utils;

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;

import javax.net.ssl.HttpsURLConnection;

public class HttpWebServiceHandlerSample {

    static String response = null;


    public HttpWebServiceHandlerSample() {

    }


    /**
     * Making service call
     *
     * @url - url to make request
     * @method - http request method
     * @params - http request params
     */


    // Get Request using HttpURLConnection  Code
    public String makeGetServiceCall(String requestURL, HashMap<String, String> postDataParams) {

        InputStream inputStream = null;

        HttpURLConnection conn = null;

        String response = "";
        try {
                /* forming th java.net.URL object */


            String newRequestURL = requestURL + getQueryString(postDataParams);

            URL url = new URL(newRequestURL);
            Log.i("URL ", newRequestURL);

            conn = (HttpURLConnection) url.openConnection();

                 /* optional request header */
            conn.setRequestProperty("Content-Type", "application/json");

                /* optional request header */
            conn.setRequestProperty("Accept", "application/json");

            //  urlConnection.setConnectTimeout(100000);

                /* for Get request */
            conn.setRequestMethod("GET");

            int statusCode = conn.getResponseCode();

                /* 200 represents HTTP OK */
            if (statusCode == 200) {

                inputStream = new BufferedInputStream(conn.getInputStream());

                response = convertInputStreamToString(inputStream);


            } else {
                response = Constants.NetWorkErrorMSG;
            }

        } catch (Exception e) {
            //    Log.i("Selltis N/w Error", e.getLocalizedMessage());
            response = Constants.NetWorkErrorMSG;

        } finally {

            if (conn != null)
                conn.disconnect();
        }

        Log.i("RESPONSE", response);
        return response; // return response

    }


    // Convert all key/Value pairs to URL request parameters
    private String getQueryString(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();
    }


    // convert InputStream to String
    private String convertInputStreamToString(InputStream inputStream) throws IOException {

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        String line = "";
        String result = "";

        while ((line = bufferedReader.readLine()) != null) {
            result += line;
        }

            /* Close Stream */
        if (null != inputStream) {
            inputStream.close();
        }

        return result;
    }


    // POST Request using HttpURLConnection  Code
    public String makePostServiceCall(String requestURL, String postJosnData) {
        InputStream inputStream = null;
        URL url;
        String response = "";
        HttpURLConnection conn = null;
        try {
            url = new URL(requestURL);

            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(10000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);

                 /* optional request header */
            conn.setRequestProperty("Content-Type", "application/json");

                /* optional request header */
            conn.setRequestProperty("Accept", "application/json");

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(postJosnData);

            //    Log.i("POST URL", url.toString());
            //   Log.i("POST DATA", postJosnData);

            writer.flush();
            writer.close();
            os.close();
            int responseCode = conn.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {

                inputStream = new BufferedInputStream(conn.getInputStream());

                response = convertInputStreamToString(inputStream);


            } else {
                response = Utils.ServerErrorMessage;

            }
        } catch (Exception e) {

            //   Log.i("Selltis N/w Error", e.getLocalizedMessage());
            response = Utils.ServerErrorMessage;
        } finally {

            if (conn != null)
                conn.disconnect();
        }

        return response;

    }


}