如何从改造Android获得错误响应

时间:2018-11-22 06:44:44

标签: java android retrofit2

通过此代码,我无法获得错误响应,就像我两次使用相同的电子邮件ID一样,然后我在邮递员中获得了错误响应,但是在我的应用程序中,我没有得到错误响应 所以,请您帮我摆脱困境

我的界面

public interface SignupAPI {
@FormUrlEncoded
@POST("users")
Call<ResponseBody> createUser(
    @Field("email") String email,
    @Field("password") String password,
    @Field("role") String role
);
}

我的Java代码

public class SignupClient {
private static final String BASE_URL = "http://74.207.233.160/api/v1/";
private static SignupClient mInstance;
private Retrofit retrofit;
private SignupClient(){
    retrofit = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
}
public static synchronized SignupClient getmInstance(){
    if (mInstance == null){
            mInstance = new SignupClient();
    }
    return mInstance;
}
public SignupAPI getApi(){
    return retrofit.create(SignupAPI.class);
}
}

我的活动

Call<ResponseBody> call = SignupClient.getmInstance().getApi().createUser(email, password,role);
call.enqueue(new Callback<ResponseBody>()
{
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response)
{
    if (response.isSuccessful()){
        progressBar.setVisibility(View.GONE);
        Toast.makeText(SignupActivity.this, "Account Sucessfully Created", Toast.LENGTH_SHORT).show();
    }else {
        try {
            progressBar.setVisibility(View.GONE);
            JSONObject jsonError = new 
            JSONObject(response.errorBody().string());
            Toast.makeText(SignupActivity.this, jsonError.getString("errors"),Toast.LENGTH_SHORT).show();
        } catch (JSONException e) {
            progressBar.setVisibility(View.GONE);
            e.printStackTrace();
        } catch (IOException e) {
            progressBar.setVisibility(View.GONE);
            e.printStackTrace();
        }
    }
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
    Toast.makeText(SignupActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}

Postman Error response

1 个答案:

答案 0 :(得分:0)

制作错误pojo类。

public class Errors{

@SerializedName("email")
private List<String> email;

public void setEmail(List<String> email){
    this.email = email;
}

public List<String> getEmail(){
    return email;
}
}

更改响应正文类。

public class ResponseBody {

@SerializedName("errors")
private Errors errors;

public void setErrors(Errors errors){
    this.errors = errors;
}

public Errors getErrors(){
    return errors;
}

}

然后用于

这样的api响应
      Errors errors=response.body().getErrors();