how to (simply) generate POST http request from java to do the file upload

房东的猫 提交于 2019-12-01 08:09:59

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!