Retrofit 2.0.2获取错误字符串体

时间:2016-05-11 11:55:17

标签: android retrofit

我使用Retrofit 2.0.2并且我无法获取错误体json并将其转换。 这是我的代码:

public RestClient() {
    retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    apiInterface = retrofit.create(ApiInterface.class);
}

        @FormUrlEncoded
    @POST("users/login")
    Call<Person> login(@FieldMap Map<String, String> map);

    private void login(Map<String, String> map) {
    Call<Person> call = restClient.getApiInterface().login(map);

    Log.d("Login_call", call.request().toString());

    call.enqueue(new Callback<Person>() {
        @Override
        public void onResponse(Call<Person> call, Response<Person> response) {
            Log.d("Login_call", response.isSuccessful() + " " + response.message());
            if (response.isSuccessful()) {
                Log.d("Login_call", response.body().toString());
                //editor.putString("user", new Gson().toJson(response.body()));
                //editor.apply();
            }
            else {
                Log.d("Login_call", response.errorBody().toString());
            }
        }

        @Override
        public void onFailure(Call<Person> call, Throwable t) {
            Log.d("Login_call_fail", "Fail");
        }
    });
}

在这里我的日志:

  

05-11 17:54:09.961 2606-2606 / D / Login_call:false错误请求

     

05-11 17:54:09.961 2606-2606 / D / Login_call:   的 okhttp3.ResponseBody$1@41ef0e18

如何解决这个问题?

3 个答案:

答案 0 :(得分:6)

我找到了问题的答案here也许这对某人有帮助。

首先,您应该为错误创建模型

public class ApiError {

@SerializedName("status")
private String status;

@SerializedName("message")
private String message;

public String getStatus() {
    return status;
}

public String getMessage() {
    return message;
}

@Override
public String toString() {
    return "ApiError{" +
            "status='" + status + '\'' +
            ", message='" + message + '\'' +
            '}';
}

}

第二步是创建将json转换为Error模型的类 在这里我的实施:

public class ErrorUtils {

public static ApiError parseError(RestClient client, Response<?> response) {

    Converter<ResponseBody, ApiError> converter = client.getRetrofit()
            .responseBodyConverter(ApiError.class, new Annotation[0]);

    ApiError error;

    try {
        error = converter.convert(response.errorBody());
    } catch (IOException e) {
        return new ApiError();
    }

    return error;
}

}

以及我如何使用它:

    private void login(Map<String, String> map) {
    Call<Person> call = restClient.getApiInterface().login(map);

    Log.d("Login_call", call.request().toString());

    call.enqueue(new Callback<Person>() {
        @Override
        public void onResponse(Call<Person> call, Response<Person> response) {
            Log.d("Login_call", response.isSuccessful() + " " + response.message());
            if (response.isSuccessful()) {
                Log.d("Login_call", response.body().toString());
                //editor.putString("user", new Gson().toJson(response.body()));
                //editor.apply();
            }
            else {
                Log.d("Login_call", response.code() + "");
                ApiError error = ErrorUtils.parseError(restClient, response);
                Log.d("Login_call_error", error.toString() + "");
            }
        }

        @Override
        public void onFailure(Call<Person> call, Throwable t) {
            Log.d("Login_call_fail", "Fail");
        }
    });
}

谢谢!

答案 1 :(得分:1)

   String data=response.errorBody().string();
   try {
            JSONObject jObjError = new JSONObject(data);
         Toast.makeText(getContext(),jObjError.getString("message"), 
         Toast.LENGTH_LONG).show();
      } 
  catch (Exception e) {
        Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_LONG).show();

      }

快乐编码..

答案 2 :(得分:0)

使用

class Library {
private:
    Book **books;
    int counter;
public:
    Library() {
        books = NULL;
        counter = 0;
    }
    void Add(INPUT &tmp) {
        books = new Book*[counter];
        ++counter;
    }
    void Delete() {
        --counter;
        delete[] books[counter];
        books[counter] = NULL;
    }
    int getCounter() {
        return this->counter;
    }
    ~Library() {
        delete[] books;
    }
};

您也可以同时使用两者

Gson().fromJson(response.errorBody()?.string(),Your class Name)