Java URL Post post(String urlString, HashMap values)

Here you can find the source of post(String urlString, HashMap values)

Description

post

License

Open Source License

Declaration

public static String post(String urlString, HashMap<String, String> values) throws IOException 

Method Source Code

//package com.java2s;
/**// w w  w .  ja v  a 2 s  . c o  m
 * LICENSING
 * 
 * This software is copyright by sunkid <sunkid@iminurnetz.com> and is
 * distributed under a dual license:
 * 
 * Non-Commercial Use:
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * Commercial Use:
 *    Please contact sunkid@iminurnetz.com
 */

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;

public class Main {
    public static String post(String urlString, HashMap<String, String> values) throws IOException {
        StringBuffer retval = new StringBuffer();
        URL url = new URL(urlString);

        StringBuffer data = new StringBuffer();
        for (String key : values.keySet()) {
            data.append(URLEncoder.encode(key, "UTF-8") + "=");
            data.append(URLEncoder.encode(values.get(key), "UTF-8") + "&");
        }

        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);

        OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream());
        osw.write(data.substring(0, data.length() - 1));
        osw.flush();

        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = rd.readLine()) != null) {
            retval.append(line);
        }
        osw.close();
        rd.close();

        return retval.toString();
    }
}

Related

  1. post(JSONObject json, String url)
  2. post(String url, Map parameters)
  3. post(String url, String content)
  4. post(String url, String content)
  5. post(String urlstr, String[] params)
  6. postData(String urlStr, String data)
  7. postData(URL base, String urlAddress, Map data)
  8. postForString(URL url, String data)
  9. postRequest(URLConnection conn, Map nameValuePairs)