Here you can find the source of sendPostRequest(String requestURL, Map
Parameter | Description |
---|---|
requestURL | the URL of the remote server |
params | A map containing POST data in form of key-value pairs |
Parameter | Description |
---|---|
IOException | thrown if any I/O error occurred |
public static HttpURLConnection sendPostRequest(String requestURL, Map<String, String> params) throws IOException
//package com.java2s; //License from project: Open Source License import java.io.IOException; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.Iterator; import java.util.Map; public class Main { /**/*from www.j a v a 2 s. co m*/ * Represents an HTTP connection */ private static HttpURLConnection httpConn; /** * Makes an HTTP request using POST method to the specified URL. * * @param requestURL * the URL of the remote server * @param params * A map containing POST data in form of key-value pairs * @return An HttpURLConnection object * @throws IOException * thrown if any I/O error occurred */ public static HttpURLConnection sendPostRequest(String requestURL, Map<String, String> params) throws IOException { URL url = new URL(requestURL); httpConn = (HttpURLConnection) url.openConnection(); httpConn.setUseCaches(false); httpConn.setDoInput(true); // true indicates the server returns response StringBuffer requestParams = new StringBuffer(); if (params != null && params.size() > 0) { httpConn.setDoOutput(true); // true indicates POST request // creates the params string, encode them using URLEncoder Iterator<String> paramIterator = params.keySet().iterator(); while (paramIterator.hasNext()) { String key = paramIterator.next(); String value = params.get(key); requestParams.append(URLEncoder.encode(key, "UTF-8")); requestParams.append("=").append(URLEncoder.encode(value, "UTF-8")); requestParams.append("&"); } // sends POST data OutputStreamWriter writer = new OutputStreamWriter(httpConn.getOutputStream()); writer.write(requestParams.toString()); writer.flush(); } return httpConn; } }