You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
pocketcommunityclient/app/src/main/java/com/community/pocket/util/HttpJSONResponse.java

74 lines
2.3 KiB

package com.community.pocket.util;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import okhttp3.ResponseBody;
/**
* 解析HTTP响应体
*
* @param <T> 响应实体类型
*/
public class HttpJSONResponse<T extends com.community.pocket.ui.main.ui.share.Response> implements Callback {
private Class<T> tClass;
private HttpParse<T> httpParse;
private static final String header = "Content-Type";
public HttpJSONResponse(Class<T> tClass, HttpParse<T> httpParse) {
this.tClass = tClass;
this.httpParse = httpParse;
}
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
e.printStackTrace();
Log.e(HttpJSONResponse.class.getName(), e.toString());
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) {
String contentType = response.header(header);
if (contentType != null && contentType.contains("json")) {
ResponseBody body = response.body();
if (body != null) {
Gson gson = new Gson();
try {
String message = body.string();
Log.i(HttpUtil.class.getName(), "响应数据:\n" + message);
T jsonObject = gson.fromJson(message, tClass);
if (jsonObject != null) {
httpParse.onParseOk(call, response, jsonObject);
} else {
onParseError(call, response, "无法把数据" + message + "解析为" + tClass + "类型");
}
} catch (JsonSyntaxException | IOException e) {
onParseError(call, response, "解析异常" + e);
}
} else {
onParseError(call, response, "响应体为null");
}
} else {
onParseError(call, response, "接口不是响应json数据,非法响应头" + header + "=" + contentType);
}
}
private void onParseError(@NotNull Call call, @NotNull Response response, String err) {
Log.e(HttpJSONResponse.class.getName(), err);
throw new RuntimeException(err);
}
}