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 扩展。
val requestImageFile = imageFile.asRequestBody("image/*".toMediaTypeOrNull())
Run Code Online (Sandbox Code Playgroud)
以下是如何使用 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/
| 归档时间: |
|
| 查看次数: |
7489 次 |
| 最近记录: |