Create an HttpURLConnection object and make it post its parameters to the server. - Android Network

Android examples for Network:HTTP Post

Description

Create an HttpURLConnection object and make it post its parameters to the server.

Demo Code


//package com.java2s;
import java.io.DataOutputStream;
import java.io.IOException;

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

public class Main {
    /**/*w ww.  ja  v a2s .  c  o  m*/
     * Create an <code>HttpURLConnection</code> object and make it post
     * its parameters to the Worddit server.
     * @param baseUrl The base URL of the Worddit server.
     * @param path The path to make the POST to
     * @param params URL-encoded parameters
     * @param cookie to send to the server
     * @return an <code>HttpURLConnection</code> for the connection
     * @throws IOException
     */
    public static HttpURLConnection makePost(URL baseUrl, String path,
            String params, String cookie) throws IOException {
        URL url = new URL(String.format("%s%s", baseUrl.toString(), path));
        HttpURLConnection connection = (HttpURLConnection) url
                .openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");

        // Set cookie if it was given
        if (cookie != null) {
            connection.setRequestProperty("Cookie", cookie);
        }

        connection.setRequestProperty("Content-Length",
                Integer.toString(params.getBytes().length));
        connection.setRequestProperty("Content-Language", "en-US");
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        // Send the request
        DataOutputStream wr = new DataOutputStream(
                connection.getOutputStream());
        wr.writeBytes(params);
        wr.flush();
        wr.close();
        return connection;
    }
}

Related Tutorials