OKHttp3学习之八:带参数文件上传
需求:上传手机SD卡上的文件至网络服务器端,要求同时附带Form表单参数和文件参数
在app模块的build.gradle配置
compile 'com.squareup.okhttp3:okhttp:3.4.2'
实现源码
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, "请求成功");
}
}
});
}
版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/02/25/okhttp3-learning-8-upload-files-with-parameters/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。
THE END
0
二维码
打赏
海报
OKHttp3学习之八:带参数文件上传
需求:上传手机SD卡上的文件至网络服务器端,要求同时附带Form表单参数和文件参数
在app模块的build.gradle配置
compile 'com.squareup.okhttp3:okhttp:……
文章目录
关闭
共有 0 条评论