Java HTTP Post httpPost(String url, StringBuffer data)

Here you can find the source of httpPost(String url, StringBuffer data)

Description

http Post

License

Open Source License

Declaration

public static int httpPost(String url, StringBuffer data) throws IOException 

Method Source Code


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

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 int httpPost(String url, StringBuffer data) throws IOException {
        return httpPost(url, data, null);
    }/* w ww  . j a v  a  2  s. co m*/

    public static int httpPost(String url, StringBuffer data, StringBuffer response) throws IOException {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        //add request header
        con.setRequestMethod("POST");

        // Send post request
        con.setDoOutput(true);
        try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
            wr.writeBytes(data.toString());
            wr.flush();
        }

        int responseCode = con.getResponseCode();
        if (response != null) {
            InputStream stream;
            if (responseCode >= 200 && responseCode <= 299 /*OK*/ ) {
                stream = con.getInputStream();
            } else {
                stream = con.getErrorStream();
            }
            try (BufferedReader in = new BufferedReader(new InputStreamReader(stream))) {
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
            }
        }

        con.disconnect();

        return responseCode;
    }
}

Related

  1. executePostWithCredentials(String targetURL, String urlParameters, String userName, String password)
  2. getHttpPOSTConnection(String urlStr, String charSet, Map props, Map params)
  3. httpGet(final String httpurl, final Map... requestProperties)
  4. httpPost(final String httpurl, final String data, final Map... requestProperties)
  5. httpPost(String httpUrl)
  6. httpPost(String urlToRead, String post)
  7. httpPostText(String urlStr, String textString)
  8. post(String json, String url)
  9. post(String json, String url)