加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

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

(2023-06-20 15:49:56)
分类: androidios

转:https://qa.1r1g.com/sf/ask/4106247421/


我尝试使用Retrofit 2OkHttp3将图像从 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认同)

sad*_*dat 6

您也可以使用 Kotlin 扩展。

val requestImageFile = imageFile.asRequestBody("image/*".toMediaTypeOrNull())

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有