Yuval Adam
Yuval Adam

Reputation: 165182

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.

Upvotes: 0

Views: 3416

Answers (4)

Confusion
Confusion

Reputation: 16841

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?

Upvotes: 4

Florian Sesser
Florian Sesser

Reputation: 6134

This code snippet served me well: Upload files by sending multipart request programmatically

It does not have any external dependencies, is only ~ 150 lines of code including comments and is IMHO even easier to handle than the Apache HttpClient library.

Upvotes: 1

Aashish Katta
Aashish Katta

Reputation: 1214

Try this as this worked in my case

File f = new File(filePath);
PostMethod filePost = new PostMethod(url);
Part[] parts = { new FilePart("file", f) };
filePost.setRequestEntity(new MultipartRequestEntity(parts,
filePost.getParams()));
HttpClient client = new HttpClient();
status = client.executeMethod(filePost);
logger.info("upload status: " + status);

Upvotes: 0

BalusC
BalusC

Reputation: 1108537

To the point, you need to construct an outputstream with data in the format as specified in RFC 1687 and RFC 2388. It's a lot of work, I am not going to post a kickoff code example, sorry :) The RFC however contains clear information and several examples how the data should look like. It is absolutely doable.

Upvotes: 1

Related Questions