Java HTTP Post doHttpPost(URL url, String requestBody)

Here you can find the source of doHttpPost(URL url, String requestBody)

Description

Executes a HTTP-POST Request

License

Apache License

Parameter

Parameter Description
url a parameter
requestBody a parameter

Exception

Parameter Description
IOException an exception

Declaration

public static void doHttpPost(URL url, String requestBody) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class Main {
    /**//  w w w  .ja va 2  s . com
     * Executes a HTTP-POST Request
     * 
     * @param url
     * @param requestBody
     * @throws IOException
     */
    public static void doHttpPost(URL url, String requestBody) throws IOException {
        HttpURLConnection connection = null;
        OutputStreamWriter writer = null;

        try {
            // Open the connection
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Length", String.valueOf(requestBody.length()));

            // Open the writer and write the request-body 
            writer = new OutputStreamWriter(connection.getOutputStream());
            writer.write(requestBody);
            writer.flush();

            // Even if we are not interested in the returned data we open the input stream in order to
            // make sure the request gets processed
            connection.getInputStream().close();
        }

        finally {
            if (connection != null)
                connection.disconnect();

            if (writer != null)
                writer.close();
        }
    }
}

Related

  1. doPOST(HttpURLConnection conn, InputStream input)
  2. doPost(String targetURL, String urlParameters, String contentType)
  3. doPost(String theURL, Map nameValuePairs)
  4. doPost(URL url, String body, String... args)