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

前端 未结 2 1545
栀梦
栀梦 2021-01-14 08:19

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 (feas

相关标签:
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.

    0 讨论(0)
  • 2021-01-14 08: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.

    0 讨论(0)
提交回复
热议问题