java 上传 part_java – 如何使用okhttp上传文件?

注意:这个答案是okhttp 1.x / 2.x。对于3.x,请参阅

this other answer。

来自mimecraft的Multipart类封装了整个HTTP体,可以处理常规字段:

Multipart m = new Multipart.Builder()

.type(Multipart.Type.FORM)

.addPart(new Part.Builder()

.body("value")

.contentDisposition("form-data; name=\"non_file_field\"")

.build())

.addPart(new Part.Builder()

.contentType("text/csv")

.body(aFile)

.contentDisposition("form-data; name=\"file_field\"; filename=\"file1\"")

.build())

.build();

一旦你有一个Multipart对象,剩下的就是指定正确的Content-Type头,并将body字节传递给请求。

由于您似乎正在使用我没有经验的OkHttp API的v2.0,这只是猜测代码:

// You'll probably need to change the MediaType to use the Content-Type

// from the multipart object

Request.Body body = Request.Body.create(

MediaType.parse(m.getHeaders().get("Content-Type")),

out.toByteArray());

对于OkHttp 1.5.4,这是一个从a sample snippet改编的一个我使用的一个删除的代码:

OkHttpClient client = new OkHttpClient();

OutputStream out = null;

try {

URL url = new URL("http://www.example.com");

HttpURLConnection connection = client.open(url);

for (Map.Entry entry : multipart.getHeaders().entrySet()) {

connection.addRequestProperty(entry.getKey(), entry.getValue());

}

connection.setRequestMethod("POST");

// Write the request.

out = connection.getOutputStream();

multipart.writeBodyTo(out);

out.close();

// Read the response.

if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {

throw new IOException("Unexpected HTTP response: "

+ connection.getResponseCode() + " " + connection.getResponseMessage());

}

} finally {

// Clean up.

try {

if (out != null) out.close();

} catch (Exception e) {

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值