Android Http Post httpPost(String... params)

Here you can find the source of httpPost(String... params)

Description

Makes a POST call to the server.

Parameter

Parameter Description
params 0-> Call Method = POST; 1-> URL; ... -> Params

Declaration

public static String httpPost(String... params) 

Method Source Code

//package com.java2s;

import java.io.IOException;

import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;

import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.util.Base64;

public class Main {
    /**/*w w w  .  java2  s  . c  o m*/
     * Makes a POST call to the server.
     * @param params 0-> Call Method = POST; 1-> URL; ... -> Params
     * @return
     */
    public static String httpPost(String... params) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost request = new HttpPost(params[1]);

        try {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            for (int i = 1; i + 1 < params.length; i += 2) {
                nameValuePairs.add(new BasicNameValuePair(params[i],
                        params[i + 1]));
            }
            if (!nameValuePairs.isEmpty()) {
                request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            }

            // Add the login header each time.
            String credentials = "jsvgoncalves@gmail.com" + ":" + "123456";
            String base64EncodedCredentials = Base64.encodeToString(
                    credentials.getBytes(), Base64.NO_WRAP);
            request.addHeader("Authorization", "Basic "
                    + base64EncodedCredentials);

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(request);
            System.out.println(response.toString());
            return response.toString();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            return "Client Protocol Exception";
        } catch (IOException e) {
            e.printStackTrace();
            return "POST: Bad Con";
        }
    }
}

Related

  1. writeData(HttpURLConnection conn, String boundary, File file, String mimeType, String fieldName)
  2. prepareAndSendHttpPost(String URI, ArrayList params)
  3. buildNameValuePair( Hashtable httpPost)
  4. sendPostRequest(String path, String params, String encoding)