Friday, June 1, 2012

Working with HTTP Connection API found in the JDK

While not as powerful and established as Apache Commons HTTP Client, it is sometimes easiest to use just what's shipped in the JDK. Sample code below shows how to use it, especially in regard to using POST (GET is used by default) and sending data to the server (by default it just GETs the URL and downloads data).

URL url = new URL("http://xxx.xxx.xxx.xxx/contextroot/SomeServlet");
HttpURLConnection conn = (HttpURLConnection) url();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();

//  ---- WRITE OUTPUT TO SERVER HERE ----
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is);

// ---- READ INPUT FROM SERVER HERE -----

Reference: http://download.oracle.com/javase/tutorial/networking/urls/readingWriting.html

No comments:

Post a Comment