Skip to content

Instantly share code, notes, and snippets.

@seungjin
Created March 2, 2011 03:54
Show Gist options
  • Save seungjin/850445 to your computer and use it in GitHub Desktop.
Save seungjin/850445 to your computer and use it in GitHub Desktop.
Post Method Example
import java.net.*;
import java.io.*;
public class PostMethodExample {
public static void main(String args[]) {
try {
// Construct data
String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
System.out.println("Posting data: " + data);
// Send data
URL url = new URL("http://localhost:8080/");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
wr.close();
rd.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment