如何替换已弃用的 okhttp.RequestBody.create()

ebe*_*nki 7 android image-upload okhttp retrofit2

我尝试使用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
                    );
Run Code Online (Sandbox Code Playgroud)

我在下一个方法调用中使用了前一个实例作为参数:

// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part image = MultipartBody.Part.createFormData("image", imageFile.getName(), requestImageFile);
Run Code Online (Sandbox Code Playgroud)

最后,我启动了 Retrofit 界面来完成剩下的工作:

// finally, execute the request
Call<ResponseBody> call = service.upload(image);
call.enqueue(new Callback<ResponseBody>() {
     @Override
     public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            Log.v("Upload", "success");
     }

     @Override
     public void onFailure(Call<ResponseBody> call, Throwable t) {
            Log.e("Upload error:", t.getMessage());
     }
});
Run Code Online (Sandbox Code Playgroud)

几个月前,Android Studio 没有告诉我它create()已被弃用。当我现在打开该项目时,它告诉我该项目已create()被弃用。有人知道如何解决吗?

Sha*_*nth 23

只需交换参数

RequestBody.create(MediaType.parse("image/*"), imageFile);
Run Code Online (Sandbox Code Playgroud)

到

RequestBody.create(imageFile, MediaType.parse("image/*"));
Run Code Online (Sandbox Code Playgroud)

  • 这里还有一个 Kotlin 解决方案: 1. 在 Kotlin 文件的导入部分中添加 `import okhttp3.RequestBody.Companion.toRequestBody`。2. 将文件类型的代码更改为 `imageFile.asRequest("image/*")`,或者如果您有其他内容(例如字符串),则使用 `content.toRequestType(mediaType)` (3认同)

sad*_*dat 8

您也可以使用 Kotlin 扩展。

val requestImageFile = imageFile.asRequestBody("image/*".toMediaTypeOrNull())
Run Code Online (Sandbox Code Playgroud)


Ami*_*ian 5

以下是如何使用 okhttp 中的 kotlin 扩展函数轻松完成此操作,例如: toRequestBody():

更改自:

val requestImageFile = RequestBody.create(
                            MediaType.parse("image/*"),
                            imageFile
                    );
Run Code Online (Sandbox Code Playgroud)

对此:

val requestImageFile = imageFile.toRequestBody(MediaType.parse("image/*"))
Run Code Online (Sandbox Code Playgroud)

'更多信息在这里:https ://square.github.io/okhttp/upgrading_to_okhttp_4/