如何替换已弃用的okhttp.RequestBody.create()
(2023-06-20 15:49:56)分类: androidios |
转:https://qa.1r1g.com/sf/ask/4106247421/
我尝试使用Retrofit 2和OkHttp3将图像从
Android 应用程序上传到 Django
服务器。为此,我曾经RequestBody
使用以下几行创建一个实例:
RequestBody requestImageFile =
// NOW this call is DEPRECATED
RequestBody.create(
MediaType.parse("image/*"),
// a File instance created via the path string to the image
imageFile
);
我在下一个方法调用中使用了前一个实例作为参数:
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part image = MultipartBody.Part.createFormData("image", imageFile.getName(), requestImageFile);
最后,我启动了 Retrofit 界面来完成剩下的工作:
// finally, execute the request
Call call = service.upload(image);
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
Log.v("Upload", "success");
}
@Override
public void onFailure(Call call, Throwable t) {
Log.e("Upload error:", t.getMessage());
}
});
几个月前,Android Studio
没有告诉我它create()
已被弃用。当我现在打开该项目时,它告诉我该项目已create()
被弃用。有人知道如何解决吗?
Sha*_*nth 23
只需交换参数
RequestBody.create(MediaType.parse("image/*"), imageFile);
到
RequestBody.create(imageFile, MediaType.parse("image/*"));
- 这里还有一个 Kotlin 解决方案: 1. 在 Kotlin 文件的导入部分中导入 okhttp3.RequestBody.Companion.toRequestBody。2. 将文件类型的代码更改为`imageFile.asRequest("image/*")`,或者如果您有一些其他内容(例如字符串),则使用`content.toRequestType(mediaType)` (3认同)
您也可以使用 Kotlin 扩展。
val requestImageFile = imageFile.asRequestBody("image/*".toMediaTypeOrNull())