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 响应实体类型 */ public class HttpResponse implements Callback { private Class tClass; private HttpParse httpParse; private static final String header = "Content-Type"; public HttpResponse(Class tClass, HttpParse httpParse) { this.tClass = tClass; this.httpParse = httpParse; } @Override public void onFailure(@NotNull Call call, @NotNull IOException e) { e.printStackTrace(); Log.e(HttpResponse.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 e) { onParseError(call, response, "解析异常" + e); } catch (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(HttpResponse.class.getName(), err); throw new RuntimeException(err); } }