繁体   English   中英

如何在java中使用HttpURLConnection发送多部分POST请求?

[英]How to send multipart POST request using HttpURLConnection in java?

这是我第一次发送多部分请求,在这里挖掘之后,我变得更加困惑,所以任何有关“正确”方式的帮助都会非常受欢迎。

我有一个函数,应该得到:文件路径和JSON的String表示,并使用multipart向服务器发送POST请求。

我不确定何时使用boundary"multipart/form-data"内容类型,以及addPartaddTextBody之间的区别,以及何时(或为什么)始终写入Content-Disposition: form-data; name=\\ Content-Disposition: form-data; name=\\

public String foo(String filePath, String jsonRep, Proxy proxy)
{
   File f = new File(filePath);
   HttpURLConnection connection;
   connection = (HttpURLConnection) url.openConnection(proxy);
   connection.setRequestProperty("Content-Type", "multipart/form-data"); // How should I generate boundary? Should it be added here? 

    if (myMethod == "POST")
     {
       connection.getOutputStream().write( ? Both the json string and the file bytes?? );
      }


 .... checking there is no error code etc..

 return ReadResponse(connection) // read input stream..

现在我不知道如何继续,以及如何编写文件和json字符串我看到这段代码:

MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("upfile", fileBody);
builder.addPart("text1", stringBody1);
builder.addPart("text2", stringBody2);

但我似乎无法理解它是如何与我的connection

你能帮忙吗?

示例HTML表单:

<form method="post" action="http://127.0.0.1/app" enctype="multipart/form-data">
<input type="text" name="foo" value="bar"><br>
<input type="file" name="bin"><br>
<input type="submit" value="test">
</form>

用于提交multipart表单的Java代码:

    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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM