android - 改造 2 - 字符串错误正文为空

标签 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");
        }
    });
}

最佳答案

我的答案是基于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;

}

关于android - 改造 2 - 字符串错误正文为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37853545/

相关文章:

java - 如何将sharedpref添加到Retrofit界面

javascript - 在 Android 应用程序上播放 mp3 铃声 - PhoneGap

android - 枚举结果时出错,请检查原始异常以获取详细信息

android - ActionBar 仅更改所选选项卡的颜色/可绘制对象?

android - android中的Uri vs File vs StringPath

android - 在 Retrofit 回调中访问原始响应体

c# - 签名的 apk 正在更改 post 参数名称

android - 将纯文本作为 POST 正文发送会导致改造出现问题

android - 无法在改造中使用查询

java - recyclerview 中的 radio 组不正确