cox
cox

Reputation: 476

How to use Retrofit to upload a file with http put

I am trying to upload a file with http PUT method,
I tried with OkHttp successfully, but failed with Retrofit.

Here is my codes : 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));
}

The code above succeeded.

What is the equivalent of Retrofit ?

I tried and failed : public interface UploadFileService { String CONTENT_TYPE = "image/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);

}

Upvotes: 1

Views: 771

Answers (1)

cox
cox

Reputation: 476

Remove Multipart annotation and apply Body to fileBody, I succeeded!

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

Upvotes: 1

Related Questions