Java URL Post post(String url, Map parameters)

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

Description

post

License

Open Source License

Declaration

public static String post(String url, Map<String, String> parameters) throws Exception 

Method Source Code


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

import java.io.*;

import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import java.util.Map;

public class Main {
    public static String post(String url, Map<String, String> parameters) throws Exception {
        URLConnection connection = new URL(url).openConnection();
        connection.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36");
        connection.setDoOutput(true);/* w  ww .j  av a 2 s .  co  m*/
        connection.setDoInput(true);
        OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream());
        osw.write(parametersToWWWFormURLEncoded(parameters));
        osw.flush();
        osw.close();
        Reader r = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringWriter w = new StringWriter();
        char[] buffer = new char[1024];
        int n = 0;
        while ((n = r.read(buffer)) != -1) {
            w.write(buffer, 0, n);
        }
        r.close();
        return w.toString();
    }

    public static String parametersToWWWFormURLEncoded(Map<String, String> parameters) throws Exception {
        StringBuilder s = new StringBuilder();
        for (Map.Entry parameter : parameters.entrySet()) {
            if (s.length() > 0) {
                s.append("&");
            }
            s.append(URLEncoder.encode((String) parameter.getKey(), "UTF-8"));
            s.append("=");
            s.append(URLEncoder.encode((String) parameter.getValue(), "UTF-8"));
        }
        return s.toString();
    }
}

Related

  1. post(JSONObject json, String url)
  2. post(String url, String content)
  3. post(String url, String content)
  4. post(String urlstr, String[] params)
  5. post(String urlString, HashMap values)