Java URL Post post(String urlstr, String[] params)

Here you can find the source of post(String urlstr, String[] params)

Description

post

License

LGPL

Declaration

public static String post(String urlstr, String[] params) 

Method Source Code

//package com.java2s;
/**/* w ww . j  ava  2s . co m*/
 * This file is under LGPL license , 
 * created 2011/6/24 19:30  TonyQ 
 */

import java.io.BufferedReader;

import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

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

public class Main {
    public static String post(String urlstr, String[] params) {

        try {
            // Construct data
            StringBuffer param = new StringBuffer();
            for (int i = 0; i < params.length; i += 2) {
                param.append(URLEncoder.encode(params[i], "UTF-8") + "=" + URLEncoder.encode(params[i + 1], "UTF-8")
                        + "&");
            }

            // Send data
            URL url = new URL(urlstr);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(param.toString());
            wr.flush();
            wr.close();

            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            StringBuffer content = new StringBuffer();
            while ((line = rd.readLine()) != null) {
                content.append(line + "\n");
            }

            rd.close();
            return content.toString();
        } catch (MalformedURLException ex) {
            throw new IllegalArgumentException("wrong url", ex);
        } catch (Exception ex) {
            throw new RuntimeException("we meet trouble", ex);
        }
    }
}

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 urlString, HashMap values)
  6. postData(String urlStr, String data)
  7. postData(URL base, String urlAddress, Map data)
  8. postForString(URL url, String data)