execute Post with Parameter - Android Network

Android examples for Network:HTTP Post

Description

execute Post with Parameter

Demo 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();/*w w w.java 2s  .  c  o  m*/
        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 Tutorials