Submit a HTTP POST Request

From CodeCodex

Revision as of 03:07, 16 February 2012 by Nostromo (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

The following shows to to complete an HTTP POST request.

Implementations

Java

This code is a simple method that takes a url

private static String doPost(URL url, Map<String,String> values) throws IOException {
	
	URLConnection urlConn;
	DataOutputStream printout;
	BufferedReader input;
	
	// URL connection channel.
	urlConn = url.openConnection();
	
	// Let the run-time system (RTS) know that we want input.
	urlConn.setDoInput(true);
	
	// Let the RTS know that we want output.
	urlConn.setDoOutput(true);
	
	// No caching
	urlConn.setUseCaches(false);
	
	// Specify the content type.
	urlConn.setRequestProperty("Content-Type", "text/html");
	
	// Send POST output.
	printout = new DataOutputStream(urlConn.getOutputStream());
	
	String content = "";
	for (String key : values.keySet()) {
		String value = values.get(key);
		content += URLEncoder.encode(key,"UTF-8") + "=" + URLEncoder.encode(value,"UTF-8") + "&";
	}
	
	//remove trailing &
	content = content.substring(0,content.length()-1);
	
	//send the data
	printout.writeBytes(content);
	printout.flush();
	printout.close();
	
	// Get response data.
	input = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
	String str;
	StringBuilder results = new StringBuilder();
	while (null != ((str = input.readLine()))) {
		System.out.println(str);
		results.append(str + "\n");
	}
	input.close();
	return results.toString();
}