Java HTTP Post post(String url, Map params, String charset)

Here you can find the source of post(String url, Map params, String charset)

Description

post

License

Open Source License

Declaration

public static String post(String url, Map<String, String> params, String charset) 

Method Source Code


//package com.java2s;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class Main {
    private static int connectTimeout = 10000;
    private static int readTimeout = 15000;
    private static byte[] buffer = new byte[1024];

    public static String post(String url, Map<String, String> params, String charset) {
        return post(url, params, null, charset);
    }/*from  ww w  .j  a va  2  s  .co  m*/

    public static String post(String url, Map<String, String> params, Map<String, String> header, String charset) {
        String result = "";
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            connection.setConnectTimeout(connectTimeout);
            connection.setReadTimeout(readTimeout);

            if (header != null) {
                for (Map.Entry<String, String> entry : header.entrySet()) {
                    connection.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }

            String postData = "";
            if (params != null) {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    postData += entry.getKey() + "=" + entry.getValue() + "&";
                }
            }

            OutputStream out = connection.getOutputStream();
            out.write(postData.getBytes(charset));
            out.flush();

            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            if (connection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {
                InputStream is = connection.getInputStream();
                int readCount = 0;
                while ((readCount = is.read(buffer)) > 0) {
                    bout.write(buffer, 0, readCount);
                }
                is.close();
            }
            connection.disconnect();
            result = out.toString();
        } catch (IOException e) {

        }
        return result;
    }
}

Related

  1. post(String json, String url)
  2. post(String json, String url)
  3. post(String rawUrl, String body)
  4. post(String url, int timeout, Map header)
  5. post(String url, JsonNode body)
  6. post(String url, String body, Map headers)
  7. post(String url, String payload)
  8. post(String url, String postdata, String cookie)
  9. Post(URL url, Map fields)