Upload binary file with retrofit android?

Refresh

April 2019

Views

10 time

0

I have image file to be uploaded to server. The API is to be of Content-Type:application/x-www-form-urlencoded.

Below is my interface method

@Headers("Content-Type: application/octet-stream")
@PUT
Call<UserIdentity> putUserProfileImage(@Url String url,
                                       @Body RequestBody file);

This is my method call

 RequestBody requestBody = RequestBody
            .create(MediaType.parse("application/octet-stream"), profileImage);


    appCMSUserIdentityRest.putUserProfileImage(url, requestBody).enqueue(new Callback<UserIdentity>() {
        @Override
        public void onResponse(@NonNull Call<UserIdentity> call,
                               @NonNull Response<UserIdentity> response) {
            if (response.body() != null) {
                Observable.just(response.body())
                        .onErrorResumeNext(throwable -> Observable.empty())
                        .subscribe(userIdentityAction);
            }else{
                Observable.just((UserIdentity) null)
                        .onErrorResumeNext(throwable -> Observable.empty())
                        .subscribe(userIdentityAction);
            }
        }

        @Override
        public void onFailure(@NonNull Call<UserIdentity> call, @NonNull Throwable t) {
            Observable.just((UserIdentity) null)
                    .onErrorResumeNext(throwable -> Observable.empty())
                    .subscribe(userIdentityAction);
        }
    });
}

I keep getting bad request error.

1 answers

0

Did you try in the postman? I think you should use multipart for this.