Java HTTP Post sendPost(String webURL, HashMap postOptions)

Here you can find the source of sendPost(String webURL, HashMap postOptions)

Description

send Post

License

LGPL

Declaration

public static String sendPost(String webURL, HashMap<String, String> postOptions) throws Exception 

Method Source Code


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

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;

public class Main {
    public static String sendPost(String webURL, HashMap<String, String> postOptions) throws Exception {
        URL obj = new URL(webURL);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", "Mozilla/5.0");
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        String urlParameters = "";
        for (String s : postOptions.keySet()) {
            urlParameters = urlParameters
                    + String.format("%s=%s&", new Object[] { s, URLEncoder.encode(postOptions.get(s), "UTF-8") });
        }//w  w  w  .j a  v a 2  s . co  m
        if (urlParameters.contains("&")) {
            urlParameters = urlParameters.substring(0, urlParameters.lastIndexOf('&'));
        }
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));

        StringBuffer response = new StringBuffer();
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine + "\r\n");
        }
        in.close();

        return response.toString();
    }
}

Related

  1. sendJson(URL url, String method, String data)
  2. sendJsonData(final HttpURLConnection connection, final String data)
  3. sendPost(String link, String urlParameters)
  4. sendPost(String url, String data)
  5. sendPost(String url, String urlParameters)
  6. sendPostRequest(Reader data, URL endpoint, Writer output)
  7. sendPostRequest(Reader data, URL endpoint, Writer output)
  8. sendPostRequest(String requestURL, Map params)
  9. URLPost(String strUrl, Map map)