2016-11-27 65 views
0

我沒有得到相同的結果,我在POSTMAN與改造Android lib工作。也許我做錯了什麼。如何使用android改造在請求中正確發送主體?

下面是我的代碼,我用它來調用API

@Override 
    protected Response doInBackground(Void... params) { 
     Response<UserModel> response; 
     try { 
      LoginModel loginModel = new LoginModel("password", mEmail, mPassword, "Mobile", "[email protected]"); 
      Retrofit retrofit = new Retrofit.Builder() 
        .baseUrl(Constants.BASE_URL) 
        .addConverterFactory(GsonConverterFactory.create()) 
        .build(); 
      ServiceAPI serviceAPI = retrofit.create(ServiceAPI.class); 
      Call<UserModel> call = serviceAPI.getToken(loginModel); 

      try{ 
       response = call.execute(); 
       if (response.body() == null) { 
        Log.d(getString(R.string.app_name), response.errorBody().toString()); 
        return response; 
       } else { 
        return response; 
       } 
      }catch (IOException e){ 
       Log.e(getString(R.string.app_name), e.getMessage()); 
      } 


      Thread.sleep(2000); 
     } catch (InterruptedException e) { 
      return null; 
     } 
     return null; 
    } 

界面下方的代碼

public interface ServiceAPI { 
    @POST("Token") 
    Call<UserModel> getToken(@Body LoginModel loginModel); 
} 

,其結果是: ErroBody

類LoginModel.java

public class LoginModel { 

@SerializedName("grant_type") 
private String grantType; 
private String username; 
private String password; 
@SerializedName("client_id") 
private String clientId; 
@SerializedName("client_secret") 
private String clientSecret; 

public LoginModel(String grantType, String username, String password, String clientId, String clientSecret) { 
    this.grantType = grantType; 
    this.username = username; 
    this.password = password; 
    this.clientId = clientId; 
    this.clientSecret = clientSecret; 
} 

}

隨着郵差的結果不同的是,獲得令牌校正。

enter image description here

回答

1

更新您的API

@FormUrlEncoded 
@Post("Token") 
Call<UserModel> getToken(@Field("grant_type") String grantType), 
         @Field("username") String userName, 
         @Field("password") String password 
         // etc 
         ); 

而且你的API調用

Call<UserModel> call = serviceAPI.getToken("password", mEmail, mPassword, ...); 
+0

感謝您嘗試幫助我!但我仍然有同樣的結果。根據你的回答,我編輯了我的問題。 我仍然不成功。你的袖子上有任何卡嗎? – Duk

+0

@Duk我的回答其實是錯誤的。當我看看郵差截圖時,我看到一個json對象,並認爲它是請求主體,實際上它是響應。仔細查看我可以看到API不接受json主體。 –