How to send multipart POST request using HttpURLConnection in java?

前端 未结 1 856
情书的邮戳
情书的邮戳 2021-01-12 23:16

It\'s my first time sending multipart requests and after digging here, I got even more confused so any help regarding the \"correct\" way will be very appriciated.

I

1条回答
  •  一生所求
    2021-01-13 00:07

    The sample HTML form:



    Java code for submiting the multipart form:

        MultipartEntityBuilder mb = MultipartEntityBuilder.create();//org.apache.http.entity.mime
        mb.addTextBody("foo", "bar");
        mb.addBinaryBody("bin", new File("testFilePath"));
        org.apache.http.HttpEntity e = mb.build();
    
        URLConnection conn = new URL("http://127.0.0.1:8080/app").openConnection();
        conn.setDoOutput(true);
        conn.addRequestProperty(e.getContentType().getName(), e.getContentType().getValue());//header "Content-Type"...
        conn.addRequestProperty("Content-Length", String.valueOf(e.getContentLength()));
        OutputStream fout = conn.getOutputStream();
        e.writeTo(fout);//write multi part data...
        fout.close();
        conn.getInputStream().close();//output of remote url
    

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