OkHttp上传文件到服务器,okhttp 上传文件

本文介绍如何使用OkHttp库在Java中实现文件上传,通过MultipartBody构建HTTP请求,包括设置Authorization头和上传文件。一个实际的上传测试示例和可能遇到的错误处理也被详细展示。
摘要由CSDN通过智能技术生成

compile 'com.squareup.okhttp3:okhttp:3.2.0'

import okhttp3.*

/**

*

*/

class ClientUploadUtils {

static ResponseBody upload(String url, String filePath, String fileName) throws Exception {

OkHttpClient client = new OkHttpClient()

RequestBody requestBody = new MultipartBody.Builder()

.setType(MultipartBody.FORM)

.addFormDataPart("file", fileName,

RequestBody.create(MediaType.parse("multipart/form-data"), new File(filePath)))

.build()

Request request = new Request.Builder()

.header("Authorization", "Client-ID " + UUID.randomUUID())

.url(url)

.post(requestBody)

.build()

Response response = client.newCall(request).execute();

if (!response.isSuccessful()) throw new IOException("Unexpected code " + response)

return response.body()

}

static void main(String[] args) throws IOException {

try {

String fileName = "com.jdsoft.biz.test.zip"

String filePath = "D:\\ExtJsTools\\Sencha\\Cmd\\repo\\pkgs\\test.zip"

String url = "http://localhost:9990/upload_app_package"

System.out.println(upload(url, filePath, fileName).string())

} catch (Exception e) {

e.printStackTrace()

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值