如何在Retrofit 2.2.0

时间:2017-07-31 12:02:09

标签: android retrofit2 multipart

我尝试在同一API请求中发布@Body@Part数据

如下所示

@Multipart
@POST("AccountService/MultipartProfileImageUpload")
Call<String> updateProfilePic(@Body UserIdCredentials userIdCredentials,@Part MultipartBody.Part file);

但它不起作用我收到错误

  

@Body参数不能与表单或多部分编码一起使用。   (参数#1)

完整的错误日志

  

07-31 05:01:01.644 6315-6315 / com.orbiosolutions.yabeee   E / AndroidRuntime:致命异常:主要                                                                            过程:com.orbiosolutions.yabeee,PID:6315                                                                            java.lang.RuntimeException:传递结果失败   ResultInfo {who = android:fragment:1,request = 3,result = -1,data = Intent {   (有额外的)}}到活动   {com.orbiosolutions.yabeee / com.orbiosolutions.yabeee.Activities.HomeActivity}:   java.lang.IllegalArgumentException:不能使用@Body参数   使用表单或多部分编码。 (参数#1)                                                                                方法ApiInterface.updateProfilePic                                                                                在android.app.ActivityThread.deliverResults(ActivityThread.java:3659)                                                                                在   android.app.ActivityThread.handleSendResult(ActivityThread.java:3702)                                                                                在android.app.ActivityThread.access $ 1300(ActivityThread.java:155)                                                                                在   android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1366)                                                                                在android.os.Handler.dispatchMessage(Handler.java:102)                                                                                在android.os.Looper.loop(Looper.java:135)                                                                                在android.app.ActivityThread.main(ActivityThread.java:5343)                                                                                at java.lang.reflect.Method.invoke(Native Method)                                                                                在java.lang.reflect.Method.invoke(Method.java:372)                                                                                在   com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:905)                                                                                在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)                                                                             造成:java.lang.IllegalArgumentException:@Body参数不能   与表单或多部分编码一起使用。 (参数#1)                                                                                方法ApiInterface.updateProfilePic                                                                                at retrofit2.ServiceMethod $ Builder.methodError(ServiceMethod.java:752)                                                                                at retrofit2.ServiceMethod $ Builder.methodError(ServiceMethod.java:743)                                                                                在   retrofit2.ServiceMethod $ Builder.parameterError(ServiceMethod.java:761)                                                                                在   retrofit2.ServiceMethod $ Builder.parseParameterAnnotation(ServiceMethod.java:701)                                                                                在   retrofit2.ServiceMethod $ Builder.parseParameter(ServiceMethod.java:336)                                                                                at retrofit2.ServiceMethod $ Builder.build(ServiceMethod.java:204)                                                                                at retrofit2.Retrofit.loadServiceMethod(Retrofit.java:170)                                                                                at retrofit2.Retrofit $ 1.invoke(Retrofit.java:147)                                                                                在java.lang.reflect.Proxy.invoke(Proxy.java:397)                                                                                在$ Proxy0.updateProfilePic(未知来源)                                                                                在   com.orbiosolutions.yabeee.Fragments.ProfileFragment.uploadProfilImg(ProfileFragment.java:191)                                                                                在   com.orbiosolutions.yabeee.Fragments.ProfileFragment.onCropImg(ProfileFragment.java:527)                                                                                在   com.orbiosolutions.yabeee.Fragments.ProfileFragment.onActivityResult(ProfileFragment.java:506)                                                                                在android.app.Activity.dispatchActivityResult(Activity.java:6222)                                                                                在android.app.ActivityThread.deliverResults(ActivityThread.java:3655)                                                                                 ......还有10个

请有人帮我解决这个问题

3 个答案:

答案 0 :(得分:1)

通过This回答的引用,我做了这样的修改,并且工作正常。

请求

RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
        MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("image", file.getName(), requestBody);
        MultipartBody.Part id = MultipartBody.Part.createFormData("userId", userId);
        //Creating a rest adapter
        ApiInterface apiService =
                ApiClient.getClient().create(ApiInterface.class);

        Call<ProfilePicUpdateResponse> call = apiService.updateProfilePic(id,fileToUpload);
        call.enqueue(new Callback<ProfilePicUpdateResponse>() {
            @Override
            public void onResponse(Call<ProfilePicUpdateResponse> call, Response<ProfilePicUpdateResponse> response) {

                loading.dismiss();
                if (response.isSuccessful()) {
                    Log.e("Success", new Gson().toJson(response.body()));
                }
                else
                {
                    loading.dismiss();
                    csActivity.showMsg(getResources().getString(R.string.something_error));
                }
            }

            @Override
            public void onFailure(Call<ProfilePicUpdateResponse> call, Throwable t) {

                loading.dismiss();
                Log.d("=========>>", t.getMessage().toString());
                Log.d("============>>>", "Failure");
            }
        });

<强> InterfaceClass

 @Multipart
    @POST("AccountService/MultipartProfileImageUpload")
    Call<ProfilePicUpdateResponse> updateProfilePic(@Part MultipartBody.Part userId, @Part MultipartBody.Part file);

答案 1 :(得分:0)

发布此

name=test

到此

CREATE OR REPLACE procedure SYS.SYSChangePassword(
  pUsername in varchar2, 
  pNewPassword in varchar2,
  pResult out varchar2(300))  as

begin
  execute immediate 'alter user '||pUsername||' identified by "' || pNewPassword || '";';
  pResult := 'New password for '|| pUsername||' has been set:  '|| pNewPassword ;
exception
  WHEN OTHERS THEN
    pResult := SQLERRM;
end;
/

并在服务器端以参数获取请求正文

答案 2 :(得分:-1)

使用以下代码:

接口:

 @Multipart
@POST("/ws_services.php?action=imageupload")
public void imageupload(@Part("image") TypedFile file, Callback<Example> callback);

Activity.java

                 TypedFile typedFile = new TypedFile("image/*", new File(file.getAbsolutePath()));

                    ApiHandler.getApiService().imageupload(typedFile, new Callback<Example>() {
                        @Override
                        public void success(Example example, Response response) {
                            try {
                                String status = example.getSuccess();
                                if (status.equals("1"))
                                {
                                    Toast.makeText(getApplication(),example.getMessage(),Toast.LENGTH_SHORT).show();

                                }
                                else
                                {
                                    Toast.makeText(getApplication(),example.getMessage(),Toast.LENGTH_SHORT).show();
                                }
                            } catch (Exception e) {

                                Log.e("status", "0");
                            }
                        }

                        @Override
                        public void failure(RetrofitError error) {
                            Log.e("retrofit error log", error.toString());
                        }
                    });