Skip to content

Instantly share code, notes, and snippets.

@gregarmer
Created August 17, 2014 03:13
Show Gist options
  • Save gregarmer/6360f46c92a406a80bff to your computer and use it in GitHub Desktop.
Save gregarmer/6360f46c92a406a80bff to your computer and use it in GitHub Desktop.
Simple HTTP POST in Java
/*
* Java POST Example
*/
package postit;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.io.DataOutputStream;
import java.io.DataInputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Greg
*/
public class Main {
/**
* Pretend you're a script...
*/
public static void main(String[] args) {
final String server = "somewhere.ontheinter.net";
URL url = null;
try {
url = new URL("http://" + server + "/we-expect-post/data");
} catch (MalformedURLException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
HttpURLConnection urlConn = null;
try {
// URL connection channel.
urlConn = (HttpURLConnection) url.openConnection();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
// Let the run-time system (RTS) know that we want input.
urlConn.setDoInput (true);
// Let the RTS know that we want to do output.
urlConn.setDoOutput (true);
// No caching, we want the real thing.
urlConn.setUseCaches (false);
try {
urlConn.setRequestMethod("POST");
} catch (ProtocolException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
try {
urlConn.connect();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
DataOutputStream output = null;
DataInputStream input = null;
try {
output = new DataOutputStream(urlConn.getOutputStream());
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
// Specify the content type if needed.
//urlConn.setRequestProperty("Content-Type",
// "application/x-www-form-urlencoded");
// Construct the POST data.
String content =
"name=" + URLEncoder.encode("Greg") +
"&email=" + URLEncoder.encode("greg at code dot geek dot sh");
// Send the request data.
try {
output.writeBytes(content);
output.flush();
output.close();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
// Get response data.
String str = null;
try {
input = new DataInputStream (urlConn.getInputStream());
while (null != ((str = input.readLine()))) {
System.out.println(str);
}
input.close ();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment