|
| 1 | +package com.cottacush.android.libraries.utils; |
| 2 | + |
| 3 | +import com.google.gson.JsonElement; |
| 4 | + |
| 5 | +import org.json.JSONException; |
| 6 | +import org.json.JSONObject; |
| 7 | + |
| 8 | +import java.io.IOException; |
| 9 | + |
| 10 | +import okhttp3.ResponseBody; |
| 11 | + |
| 12 | +/** |
| 13 | + * @author Adegoke Obasa <goke@cottacush.com> |
| 14 | + */ |
| 15 | + |
| 16 | +public class HttpResponseUtils { |
| 17 | + |
| 18 | + private JsonElement successBody; |
| 19 | + private JSONObject errorBody; |
| 20 | + |
| 21 | + public static final String ERROR_MESSAGE = "An unexpected network error occurred."; |
| 22 | + |
| 23 | + public HttpResponseUtils(JsonElement successBody, ResponseBody errorBody) { |
| 24 | + this.successBody = successBody; |
| 25 | + if (errorBody != null) { |
| 26 | + try { |
| 27 | + if (errorBody != null) { |
| 28 | + this.errorBody = new JSONObject(errorBody.string()); |
| 29 | + } |
| 30 | + } catch (JSONException | IOException e) { |
| 31 | + e.printStackTrace(); |
| 32 | + } |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + public boolean isSuccess() { |
| 37 | + return (successBody != null && successBody.getAsJsonObject().has("status") && |
| 38 | + successBody.getAsJsonObject().get("status").getAsString().equalsIgnoreCase("success")); |
| 39 | + } |
| 40 | + |
| 41 | + public JsonElement getData() { |
| 42 | + return successBody.getAsJsonObject().get("data"); |
| 43 | + } |
| 44 | + |
| 45 | + public JsonElement getDataAsObject() { |
| 46 | + return successBody.getAsJsonObject().get("data").getAsJsonObject(); |
| 47 | + } |
| 48 | + |
| 49 | + public JsonElement getDataAsArray() { |
| 50 | + return successBody.getAsJsonObject().get("data").getAsJsonArray(); |
| 51 | + } |
| 52 | + |
| 53 | + public String getErrorMessage() { |
| 54 | + if (errorBody == null) { |
| 55 | + return ERROR_MESSAGE; |
| 56 | + } |
| 57 | + try { |
| 58 | + return errorBody.getString("message"); |
| 59 | + } catch (JSONException e) { |
| 60 | + e.printStackTrace(); |
| 61 | + } |
| 62 | + return ERROR_MESSAGE; |
| 63 | + } |
| 64 | + |
| 65 | + public String getCode() { |
| 66 | + if (errorBody == null) { |
| 67 | + return "-1"; |
| 68 | + } |
| 69 | + try { |
| 70 | + return errorBody.getString("code"); |
| 71 | + } catch (JSONException e) { |
| 72 | + e.printStackTrace(); |
| 73 | + } |
| 74 | + return "-1"; |
| 75 | + } |
| 76 | + |
| 77 | +} |
0 commit comments