views:

360

answers:

2

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.

+1  A: 

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.

BalusC
hyper-link is right, but hyper-text is not. :)
Adeel Ansari
Added RFC 2388 for the same story without the HTML part :)
BalusC
+2  A: 

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?

Confusion
I do have some integration issues, but if it's easier then implementing the request encoding, I'll go with an external lib. thanks :)
Yuval A