java多文件post请求,如何在Java中使用HttpURLConnection发送多部分POST请求?

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 have a function, that should get : file path and a String representation of JSON and send POST request to the server using multipart.

I'm not sure when to use the boundary and "multipart/form-data" content type, and the difference between addPart and addTextBody, and when (or why) it is always written 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..

Now I'm not sure how to continue, and how to write the file and the json string

I saw this code:

MultipartEntityBuilder builder = MultipartEntityBuilder.create();

builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

builder.addPart("upfile", fileBody);

builder.addPart("text1", stringBody1);

builder.addPart("text2", stringBody2);

But I can't seem to understand how it is connected to my connection.

Can you please help?

解决方案

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值