How to (simply) generate an HTTP POST request from java to download a file

I would like to download files from a java application / applet using the http post event. I would like to avoid using any library not included in SE unless there is another (possible) option.
While I come up with a very simple solution.
- Create a String (Buffer) and fill it with a compatible header ( http://www.ietf.org/rfc/rfc1867.txt )
- Open a connection to the server URL.openConnection () and write the contents of this file to OutputStream.
I also need to manually convert the binary to a POST event.

Hope there is a better, easier way to do this?

+3
source share
2 answers

You need to use the java.net.URLand classes java.net.URLConnection.

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

Here is 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 still have to tell urlencode () your POST data before writing it to the connection.

+8
source

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

+3
source

All Articles