Retrofit 2 - 字符串错误正文为空

时间:2016-06-16 08:16:01

标签: android retrofit2

服务器在成功时返回JSON个对象,在错误情况下返回简单String

JSON解析为对象没有问题。因为response.errorBody().string()为空,我想解析错误时问题就出现了。

当我使用Postman发送相同的请求时,响应如下: enter image description here

我无法读到这个错误......有人遇到过这样的问题吗?

代码

gradle

compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
compile 'com.squareup.okhttp:okhttp:2.6.0'

RestClient.java

private static GitApiInterface gitApiInterface;
...
public static GitApiInterface getClient() {
    if (gitApiInterface == null) {

        OkHttpClient okClient = new OkHttpClient();
        okClient.interceptors().add(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Response response = chain.proceed(chain.request());
                return response;
            }
        });


        Retrofit client = new Retrofit.Builder()
                .baseUrl(URL_BASE)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        gitApiInterface = client.create(GitApiInterface.class);
    }
    return gitApiInterface;
}

ApiInterface.java

public interface ApiInterface {

@POST("/register/user/{email}/")
        Call<User> postRegisterUser(@Path(value = "email", encoded = true) String email,
                                      @Query("firstname") String firstName,
                                      @Query("lastname") String lastName,
                                      @Query("country") String country,
                                      @Query("phone") String phone,
                                      @Query("deviceid") String deviceId);
...

ServerRequests.java

 public void registerUser(@NonNull String email,
                         @NonNull String firstName,
                         @NonNull String lastName,
                         @NonNull String country,
                         @NonNull String phone,
                         @NonNull String deviceId,
                         @NonNull final RegisterUserCallback callback) {
    showProgressBar();

    RestClient.GitApiInterface service = RestClient.getClient();
    Call<User> call = service.postRegisterUser(email, firstName, lastName, country,  phone, deviceId);
    call.enqueue(new Callback<User>() {
        @Override
        public void onResponse(Call<User> call, Response<User> response) {
            hideProgressBar();

            User user = response.body(); //this works great

            if (response.isSuccess()) {
                Log.d(TAG, "REGISTER success: " + response.message());
                callback.onRegisteredUser(user);

            } else {
                try {
                    Log.e(TAG, "REGISTER fail: " + response.errorBody().string()); //empty error body
                    callback.onRegisterFailed(response.errorBody().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onFailure(Call<User> call, Throwable t) {
            hideProgressBar();

            callback.onRegisterFailed("error");
        }
    });
}

1 个答案:

答案 0 :(得分:2)

我的回答是基于 HttpLoggingInterceptor 类。

我在参数response.errorBody()中给出了getStatusError()方法。

private StatusError getStatusError(ResponseBody responseBody) {
    StatusError statusError = null;

    if (responseBody != null) {
        try {
            BufferedSource source = responseBody.source();

            if (source != null) {
                source.request(Long.MAX_VALUE); // Buffer the entire body.
                Buffer buffer = source.buffer();

                Charset charset = UTF8;
                MediaType contentType = responseBody.contentType();
                if (contentType != null) {
                    charset = contentType.charset(UTF8);
                }

                String string = buffer.clone().readString(charset);

                if (!TextUtils.isEmpty(string)) {
                    GsonBuilder gsonBuilder = new GsonBuilder();
                    Gson gson = gsonBuilder.create();

                    statusError = gson.fromJson(string, StatusError.class);
                }
            }

        } catch (Exception e) {
            LogUtils.LOGW(TAG, "Impossible to get StatusError stream", e);
        }
    }

    return statusError;
}

StatusError是一个映射(JSON)元素的POJO类:

public class StatusError {

@SerializedName("message")
public String message;

@SerializedName("errors")
public ArrayList<ErrorDetail> errors;

}