【问题标题】:POST Image using Retrofit 2.0使用 Retrofit 2.0 发布图像
【发布时间】:2017-03-28 20:02:32
【问题描述】:

我正在尝试使用具有以下要求的 POST 请求上传图像:

参数名称:imageFile
参数类型:文件
要上传的文件。它必须作为多部分包含在请求的正文中,其中 value=image 和 type=image/*。

这是请求定义:

    @Multipart
    @POST("sample/uploadImage")
    Call<ImageResponse> UploadImage(@Part MultipartBody.Part file);

这是代码:

  RequestBody fbodyRequest = RequestBody.create(MediaType.parse("image/*"), destination);

[...]

RetrofitInterface apiService =
                retrofit.create(RetrofitInterface.class);
        Call<ImageResponse> call = apiService.UploadImage(fbodyRequest);
        call.enqueue(new Callback<ImageResponse>() {...

提前致谢。

【问题讨论】:

标签: android post retrofit2


【解决方案1】:

您可以尝试以下代码以文件类型上传图片。

改造接口类:

public interface RetrofitInterface {
  @Multipart
    @POST("v1/photo/{deviceid}/")
    public Call<PhotoModel> photoValues(@Path("deviceid") String deviceid, @Query("key") String key, @Part MultipartBody.Part filePart)

    final OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .readTimeout(50000, TimeUnit.SECONDS)
            .connectTimeout(50000, TimeUnit.SECONDS)
            .build();

    public static final Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(AppConstants.mBaseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .client(okHttpClient)
            .build();
}

首先获取图像文件并转换为 FilePart 类型然后只有我们可以 通过改造 api 发送。它会正常工作。

主类:

RetrofitInterface service = RetrofitInterface.retrofit.create(RetrofitInterface.class);
        Call<PhotoModel> call = service.photoValues(deviceid, AppConstants.mApiKey, filePart);
        call.enqueue(new Callback<PhotoModel>() {
            @Override
            public void onResponse(Call<PhotoModel> call, Response<PhotoModel> response) {
                .....
            }

            @Override
            public void onFailure(Call<PhotoModel> call, Throwable t) {
                .....
            }
        });

【讨论】:

    猜你喜欢
    • 2016-04-06
    • 2023-04-10
    • 1970-01-01
    • 2016-08-03
    • 1970-01-01
    • 2015-01-28
    • 2013-10-06
    • 2017-04-05
    • 1970-01-01
    相关资源
    最近更新 更多