Java HTTP Post Post(URL url, Map fields)

Here you can find the source of Post(URL url, Map fields)

Description

Post

License

Open Source License

Declaration

public static HttpURLConnection Post(URL url, Map fields) throws IOException 

Method Source Code


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

import java.util.*;
import java.io.*;
import java.net.*;

public class Main {
    public static HttpURLConnection Post(URL url, Map fields) throws IOException {
        String body;/*w  ww. j av  a  2  s.  co m*/
        body = encodeToForm(fields);

        return Post(url, body);
    }

    public static HttpURLConnection Post(URL url, String body) throws IOException {
        OutputStream os;
        HttpURLConnection conn;
        String len;

        conn = (java.net.HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setRequestProperty("User-Agent", "mod_pubsub.java/0.1");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        len = Integer.toString(body.length());
        conn.setRequestProperty("Content-Length", len);
        conn.connect();
        os = conn.getOutputStream();

        // send content body
        for (int i = 0; i < body.length(); i++) {
            os.write((byte) body.charAt(i));
        }

        return conn;
    }

    public static String encodeToForm(Map msg) {
        StringBuffer sb = new StringBuffer();

        String name;
        Object value;
        Iterator it = msg.keySet().iterator();
        while (it.hasNext()) {
            name = (String) it.next();
            value = URLEncoder.encode((String) msg.get(name));
            sb.append(name + "=" + value);
            if (it.hasNext())
                sb.append("&");
        }
        return sb.toString();
    }
}

Related

  1. post(String url, JsonNode body)
  2. post(String url, Map params, String charset)
  3. post(String url, String body, Map headers)
  4. post(String url, String payload)
  5. post(String url, String postdata, String cookie)
  6. post(URL url, Map values)
  7. post(URL url, String content)
  8. post(URL url, String contentType, byte[] data)
  9. postCall(JsonObject json, String url)