尝试使用Retrofit 2和rxjava通过api调用上传个人资料图片。响应始终给我错误,即422 Unprocessable Entity。给出我的代码并需要建议来克服这一点。
@Multipart
@POST("api/update-profile-picture")
Observable<ProfilePicture> updateProfilePicture(
@Header("Authorization") String accessToken,
@Part("profile_picture") RequestBody profile_picture
);
// calling presenter method to update profile picture
public void updateProfilePictureImage(File file){
getMvpView().showProgress();
RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
//MultipartBody.Part body = MultipartBody.Part.createFormData("profile_picture", file.getName(), reqFile);
oyeBuddyService.updateProfilePicture("Bearer" + " " + mPrefs.getOyeUserAccessToken(), reqFile)
.subscribeOn(mNewThread)
.observeOn(mMainThread)
.subscribe(new Observer<ProfilePicture>() {
@Override
public void onCompleted() {
getMvpView().hideProgress();
}
@Override
public void onError(Throwable e) {
getMvpView().hideProgress();
Log.e("error: ",e.getMessage());
}
@Override
public void onNext(ProfilePicture profilePicture) {
Log.e("response: ", profilePicture.toString());
getMvpView().onProfilePictureUpdated(profilePicture.profile_picture_url);
}
});
}
回应---&gt;
RetrofitModule: Received response for http://174.138.64.95/api/update-profile-picture in 4540.6ms
Date: Wed, 04 Oct 2017 10:30:53 GMT
Server: Apache/2.4.18 (Ubuntu)
Vary: Authorization
Cache-Control: no-cache, private
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 59
Content-Length: 99
Keep-Alive: timeout=5, max=99
Connection: Keep-Alive
Content-Type: application/json
E/error:: HTTP 422 Unprocessable Entity
答案 0 :(得分:1)
您应该将@Part MultipartBody.Part profile_picture
而不是RequestBody传递给Retrofit界面。
答案 1 :(得分:0)
您需要添加标题:
接受= * / *
例如:
httpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
Request request = original.newBuilder()
.header("Accept", "*/*")
.method(original.method(), original.body())
.build();
return chain.proceed(request);
}
}