Extreme Java When vanilla Java is not enough

4Jan/080

HTTP POST download with Java’s URL class

This is easy, but I always forget the recipe. I need to download and process a file using a POST request. The code is:

URL url = new URL(FORM_URL);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
 
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
out.write("field=value&field=value&...");
out.flush();
 
InputStreamReader isr = new InputStreamReader(conn.getInputStream());
BufferedReader in = new BufferedReader(isr);
String line;
 
while ((line = in.readLine()) != null) {
    // do something
}
 
out.close();
in.close();

The only catch is to use URLEncoder.encode to translate keys and values to the x-form-url-encoded style.

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

(required)


*

No trackbacks yet.