Search code examples
javahttpmultipartform-datamultipart

Creating a post request including a multipart file upload


I am writing a simple snippet which sends a simple post request.

Currently I am building the request like so:

    // Construct data
    String data = URLEncoder.encode("param1", "UTF-8") + "=" + URLEncoder.encode("val1", "UTF-8");
    data += "&" + URLEncoder.encode("param2", "UTF-8") + "=" + URLEncoder.encode("val2", "UTF-8");

    // Send data
    URL url = new URL("http://server:8080/servlet/upload");
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();

    // do stuff with response....

This works, as of now. But I need to add a file upload as a multipart POST request. How can I do this? I would like to avoid using HttpClient from commons if possible.


Solution

  • Currently you aren't using HTTP at all. If you intend to do a POST, the first thing you need to do is make sure you send the correct headers and such, so you are actually engaging in an HTTP connection. Then you need to follow RFC 1867 ( https://www.rfc-editor.org/rfc/rfc1867 ) to properly encode the file contents into your POST. This is not easy, which is why there are libraries out there which do this for you. So I have to ask: why avoid HttpClient? I've always used it for this purpose. It's reliable, complete and performant. Are you short on (memory/disk) space?