Posts Tagged ‘download’

HTTP POST download with Java’s URL class

Friday, January 4th, 2008

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.