how to (simply) generate POST http request from ja

2020-03-26 05:01发布

问题:

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?

回答1:

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.



回答2:

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.