Java URL Parameter Builder sendPostRequest(String path, Map params, String enc)

Here you can find the source of sendPostRequest(String path, Map params, String enc)

Description

send Post Request

License

Apache License

Declaration

public static boolean sendPostRequest(String path, Map<String, String> params, String enc) throws Exception 

Method Source Code

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

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import java.net.URLEncoder;
import java.util.Map;

public class Main {
    public static boolean sendPostRequest(String path, Map<String, String> params, String enc) throws Exception {
        StringBuilder sb = new StringBuilder();
        if (params != null && !params.isEmpty()) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                sb.append(entry.getKey()).append('=').append(URLEncoder.encode(entry.getValue(), enc)).append('&');
            }//from  www  .j a va2s  .  co m
            sb.deleteCharAt(sb.length() - 1);
        }
        byte[] entitydata = sb.toString().getBytes();
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setConnectTimeout(5 * 1000);
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", String.valueOf(entitydata.length));
        OutputStream outStream = conn.getOutputStream();
        outStream.write(entitydata);
        outStream.flush();
        outStream.close();
        if (conn.getResponseCode() == 200) {
            return true;
        }
        return false;
    }
}

Related

  1. parse_parameters(String input)
  2. parseGetParameters(HttpExchange exchange)
  3. parseParameters(final String value)
  4. parseResponseParams(String body)
  5. sendGetRequest(String path, Map params, String enc)
  6. serializeParameters(final Map parameters)
  7. serializeParameters(final Map params)
  8. stringToMap(String input)
  9. stringToMap(String input)