views:

6302

answers:

3

I would like to upload files from java application/applet using POST http event. I would like to avoid to use any library not included in SE, unless there is no other (feasible) option.
So far I come up only with very simple solution.
- Create String (Buffer) and fill it with compatible header (http://www.ietf.org/rfc/rfc1867.txt)
- Open connection to server URL.openConnection() and write content of this file to OutputStream.
I also need to manually convert binary file into POST event.

I hope there is some better, simpler way to do this?

+2  A: 

You need to learn about the chunked encoding used in newer versions of HTTP. The Apache HttpClient library is a good reference implementation to learn from.

Josh
+4  A: 

You need to use the java.net.URL and java.net.URLConnection classes.

There are some good examples at http://java.sun.com/docs/books/tutorial/networking/urls/readingWriting.html

Here's some quick and nasty code:

public void post(String url) throws Exception {
 URL u = new URL(url);
 URLConnection c = u.openConnection();

 c.setDoOutput(true);
 if (c instanceof HttpURLConnection) {
  ((HttpURLConnection)c).setRequestMethod("POST");
 }

 OutputStreamWriter out = new OutputStreamWriter(
  c.getOutputStream());

 // output your data here

 out.close();

 BufferedReader in = new BufferedReader(
       new InputStreamReader(
         c.getInputStream()));

 String s = null;
 while ((s = in.readLine()) != null) {
  System.out.println(s);
 }
 in.close();
}

Note that you may still need to urlencode() your POST data before writing it to the connection.

Alnitak
A: 

I Don't have an answer to this question but I want to thank Alnitak for their answer it helped me complete a crucial portion of a project I am working on.

JoshOiknine