Pages

Friday, August 31, 2012

Sending a HTTP request in Java SE

Here's an example on how to send a HTTP request in Java SE using the HttpURLConnection class. Basically, the sample code below will allow you to send a POST method request with 2 parameters.

URL siteUrl = new URL("http://www.youractionurl.com");
HttpURLConnection conn = (HttpURLConnection) siteUrl.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);

DataOutputStream out = new DataOutputStream(conn.getOutputStream());
String content = "param1=1234&param2=user1234";
out.writeBytes(content);
out.flush();
out.close();

BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    while(in.readLine() != null) {
         System.out.println(in.readLine());
    }
in.close();

The HttpURLConnection class extends the URLConnection superclass & supports HTTP-specific features to provide a communication link between application and URL. You can just check the Java SE API for more information. :)

No comments:

Post a Comment