Upload files from Java client to a HTTP server

Posted on

Problem :

I’d like to upload a few files to a HTTP server. Basically what I need is some sort of a POST request to the server with a few parameters and the files. I’ve seen examples of just uploading files, but didn’t find how to also pass additional parameters.

What’s the simplest and free solution of doing this? Does anyone have any file upload examples that I could study? I’ve been googling for a few hours, but (maybe it’s just one of those days) couldn’t find exactly what I needed. The best solution would be something that doesn’t involve any third party classes or libraries.

Solution :

You’d normally use java.net.URLConnection to fire HTTP requests. You’d also normally use multipart/form-data encoding for mixed POST content (binary and character data). Click the link, it contains information and an example how to compose a multipart/form-data request body. The specification is in more detail described in RFC2388.

Here’s a kickoff example:

String url = "http://example.com/upload";
String charset = "UTF-8";
String param = "value";
File textFile = new File("/path/to/file.txt");
File binaryFile = new File("/path/to/file.bin");
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
String CRLF = "rn"; // Line separator required by multipart/form-data.

URLConnection connection = new URL(url).openConnection();
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

try (
OutputStream output = connection.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
) {
// Send normal param.
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name="param"""").append(CRLF)

Leave a Reply

Your email address will not be published. Required fields are marked *