Android Http Post executePost(String url, String parameters)

Here you can find the source of executePost(String url, String parameters)

Description

execute Post

Declaration

public static String executePost(String url, String parameters)
            throws IOException 

Method Source Code

//package com.java2s;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import java.net.HttpURLConnection;
import java.net.URL;

public class Main {
    public static String executePost(String url, String parameters)
            throws IOException {

        URL request = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) request
                .openConnection();//from w ww  .  ja  v  a  2 s .c om
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("User-Agent", "StripeConnectAndroid");
        connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");
        connection.setRequestProperty("charset", "utf-8");
        connection.setRequestProperty("Content-Length",
                "" + Integer.toString(parameters.getBytes().length));
        connection.setUseCaches(false);

        DataOutputStream wr = new DataOutputStream(
                connection.getOutputStream());
        wr.writeBytes(parameters);
        wr.flush();
        wr.close();

        String response = streamToString(connection.getInputStream());
        connection.disconnect();
        return response;

    }

    private static String streamToString(InputStream is) throws IOException {
        String str = "";

        if (is != null) {
            StringBuilder sb = new StringBuilder();
            String line;

            try {
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(is));

                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }

                reader.close();
            } finally {
                is.close();
            }

            str = sb.toString();
        }

        return str;
    }
}

Related

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