Java HTTP Post httpPost(String urlToRead, String post)

Here you can find the source of httpPost(String urlToRead, String post)

Description

Performs synchronous HTTP POST request with raw data, returns the response.

License

Open Source License

Parameter

Parameter Description
urlToRead a parameter
post a parameter

Exception

Parameter Description
Exception an exception

Declaration

public static String httpPost(String urlToRead, String post) throws Exception 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.URL;

public class Main {
    /**/*from   w  w w  . j a  v a2 s  .  c om*/
     * Performs synchronous HTTP POST request with raw data, returns the response.
     * @param urlToRead
     * @param post
     * @return
     * @throws Exception
     */
    public static String httpPost(String urlToRead, String post) throws Exception {
        return httpPost(urlToRead, post, Proxy.NO_PROXY);
    }

    public static String httpPost(String urlToRead, String post, Proxy proxy) throws Exception {
        StringBuilder result = new StringBuilder();
        URL url = new URL(urlToRead);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy);
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        final OutputStream os = conn.getOutputStream();
        final BufferedOutputStream bos = new BufferedOutputStream(os);
        bos.write(post.getBytes("UTF-8"));
        bos.close();

        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        rd.close();
        return result.toString();
    }
}

Related

  1. getHttpPOSTConnection(String urlStr, String charSet, Map props, Map params)
  2. httpGet(final String httpurl, final Map... requestProperties)
  3. httpPost(final String httpurl, final String data, final Map... requestProperties)
  4. httpPost(String httpUrl)
  5. httpPost(String url, StringBuffer data)
  6. httpPostText(String urlStr, String textString)
  7. post(String json, String url)
  8. post(String json, String url)
  9. post(String rawUrl, String body)