Question

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.

Was it helpful?

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. The you need to follow RFC 1867 ( http://tools.ietf.org/html/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?

OTHER TIPS

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.

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top