【问题标题】:How to use Retrofit to upload a file with http put如何使用 Retrofit 通过 http put 上传文件
【发布时间】:2019-07-27 00:54:02
【问题描述】:

我正在尝试使用 http PUT 方法上传文件,
我尝试使用 OkHttp 成功,但使用 Retrofit 失败。

这是我的代码: static final String MEDIA_TYPE="image/jpeg"

// file is  a file path

RequestBody requestBody = getRequestBody(file);

OkHttpClient client = getOkHttpClient();
Request request = new Request.Builder()
        .url(url)
        .put(requestBody)
        .build();

okhttp3.Response response = response = client.newCall(request).execute();

private RequestBody getRequestBody(String filePath) {
    MediaType contentType = MediaType.parse(MEDIA_TYPE);
    return RequestBody.create(contentType, new File(filePath));
}

上面的代码成功了。

Retrofit 相当于什么?

我尝试过但失败了: 公共接口 UploadFileService { 字符串 CONTENT_TYPE = "图像/jpeg";

/** base url, just for Retrofit usage demand. */
String BASE_URL = "https://not.used.net/";

/** Must be consistent with the following uploadFile annotation. */
String UPLOAD_FILE_HTTP_METHOD = "PUT";

@Multipart
@Headers("Content-Type:" + CONTENT_TYPE)
@PUT()
Observable<Response<MinaResponse<LocalAlbum.DummyResponse>>> uploadFile(@Url String url, @Part RequestBody fileBody);

}

【问题讨论】:

    标签: http retrofit put


    【解决方案1】:

    移除Multipart注解并将Body应用到fileBody, 我成功了!

    @Headers("Content-Type:" + CONTENT_TYPE)
    @PUT()
    Observable<Response<MinaResponse<LocalAlbum.DummyResponse>>> uploadFile(@Url String url, @Body RequestBody fileBody);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-01
      • 2012-03-03
      • 2023-03-24
      • 2011-11-02
      • 2012-08-13
      • 2016-02-22
      • 2019-05-09
      • 1970-01-01
      相关资源
      最近更新 更多