2008-01-04

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();

BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
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.

No comments: