服务器在成功的情况下返回 JSON
对象,在错误的情况下返回简单的 String
。
将 JSON
解析为对象没有问题。当我想解析错误时,问题就会出现,因为 response.errorBody().string()
为空。
我无法读取此错误...有人遇到过这样的问题吗?
代码代码
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/