OKHttp3学习之八:带参数文件上传

需求:上传手机SD卡上的文件至网络服务器端,要求同时附带Form表单参数和文件参数

在app模块的build.gradle配置

1
compile 'com.squareup.okhttp3:okhttp:3.4.2'

实现源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public void uploadFile(View view) {
OkHttpClient client = new OkHttpClient();
String uploadUrl = SERVER_ADDRESS + "/upload";
String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "generated.apk";
File file = new File(filePath);

RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);

RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("username", "appblog.cn") //Form表单参数
.addFormDataPart("file", "appblog.apk", fileBody) //文件参数
.build();

Request request = new Request.Builder().url(uploadUrl).post(requestBody).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i(TAG, "请求失败: " + e.getLocalizedMessage());
}

@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
Log.i(TAG, "请求成功");
}
}
});
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :