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?

bignose
  • 30,281
  • 14
  • 77
  • 110
user40271
  • 39
  • 1
  • 1
  • 2
  • Please explain why you don't want to use an external library. Clearly it's *possible* without any external libraries, but you'll basically be duplicating the effort of (say) HttpClient (http://hc.apache.org/httpcomponents-client/index.html) – Jon Skeet Nov 24 '08 at 14:46
  • I suppose he wants to avoid using a library to reduce the applet size, reducing downloading time. – Serxipc Nov 24 '08 at 17:02

2 Answers2

8

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
  • 334,560
  • 70
  • 407
  • 495
3

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
  • 17,834
  • 7
  • 50
  • 68