Android Http Post prepareAndSendHttpPost(String URI, ArrayList params)

Here you can find the source of prepareAndSendHttpPost(String URI, ArrayList params)

Description

prepare And Send Http Post

Declaration

protected static JSONObject prepareAndSendHttpPost(String URI,
            ArrayList<NameValuePair> params) 

Method Source Code

//package com.java2s;

import android.util.Log;
import org.apache.http.protocol.HTTP;
import org.apache.http.entity.StringEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;

import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONObject;
import org.json.JSONException;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;

public class Main {
    protected static String TAG = "JSONServerNetworkUtil";
    public static final int REGISTRATION_TIMEOUT = 30 * 1000;
    protected static HttpClient mHttpClient;

    protected static JSONObject prepareAndSendHttpPost(String URI,
            ArrayList<NameValuePair> params) {
        JSONObject json = null;// ww w  . j a v a 2  s.  com
        try {
            json = new JSONObject();
            if (params != null) {
                Iterator<NameValuePair> it = params.iterator();
                while (it.hasNext()) {
                    NameValuePair pair = it.next();
                    json.put(pair.getName().toString(), pair.getValue());
                }
            }
        } catch (JSONException e) {
            Log.e(TAG, "unable to encode JSON for http request");
        }

        StringEntity se = null;
        try {
            se = new StringEntity(json.toString());
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                    "application/json"));
        } catch (Exception e) {
            Log.d(TAG, "unable to create string entity");
        }

        final HttpPost post = new HttpPost(URI);
        post.setEntity(se);

        post.setHeader("Accept", "application/json");
        post.setHeader("Content-type", "application/json");

        maybeCreateHttpClient();

        HttpResponse resp = null;
        try {

            resp = mHttpClient.execute(post);

            if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                if (Log.isLoggable(TAG, Log.VERBOSE)) {
                    Log.v(TAG, "Successful POST");
                }
                return decodeJSONResponse(resp);
            } else {
                if (Log.isLoggable(TAG, Log.VERBOSE)) {
                    Log.v(TAG, "Error POSTing: " + resp.getStatusLine());
                }
                return null;
            }
        } catch (final IOException e) {
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, "IOException when POSTING", e);
            }
            return null;
        } finally {
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, "POST completing");
            }
        }
    }

    /**
     * Configures the httpClient to connect to the URL provided.
     */
    public static void maybeCreateHttpClient() {
        if (mHttpClient == null) {
            mHttpClient = new DefaultHttpClient();
            final HttpParams params = mHttpClient.getParams();
            HttpConnectionParams.setConnectionTimeout(params,
                    REGISTRATION_TIMEOUT);
            HttpConnectionParams.setSoTimeout(params, REGISTRATION_TIMEOUT);
            ConnManagerParams.setTimeout(params, REGISTRATION_TIMEOUT);
        }
    }

    protected static JSONObject decodeJSONResponse(HttpResponse resp) {

        InputStream is = null;
        try {
            is = resp.getEntity().getContent();
        } catch (IOException e) {
            Log.d(TAG, "unable to get content from response entity");
            e.printStackTrace();
            return null;
        }

        String in = convertStreamToString(is);

        JSONObject json = null;
        try {
            json = new JSONObject(in);
        } catch (JSONException e) {
            Log.d(TAG, "could not decode JSON response from: " + in);
        }

        return json;
    }

    protected static String convertStreamToString(InputStream is) {

        BufferedReader reader = new BufferedReader(
                new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}

Related

  1. httpPost(String... params)
  2. writeData(HttpURLConnection conn, String boundary, File file, String mimeType, String fieldName)
  3. buildNameValuePair( Hashtable httpPost)
  4. sendPostRequest(String path, String params, String encoding)
  5. executePost(String url, String parameters)