From d54ed9bfe0303e7417fcfe4557c668b0ae64313b Mon Sep 17 00:00:00 2001 From: Matt Jones Date: Fri, 22 Mar 2024 14:25:02 -0500 Subject: [PATCH] fix: use util method for parsing response --- pom.xml | 4 ++-- .../switch_bot/SwitchBotDeviceApi.java | 24 ++++++++++++------- 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/pom.xml b/pom.xml index dd4609d..ca15e63 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ com.bigboxer23 switchbotapi-java - 1.1.3 + 1.1.4 switchbotapi-java https://github.com/bigboxer23/switchbotapi-java @@ -37,7 +37,7 @@ com.bigboxer23 utils - 2.0.23 + 2.0.24 org.projectlombok diff --git a/src/main/java/com/bigboxer23/switch_bot/SwitchBotDeviceApi.java b/src/main/java/com/bigboxer23/switch_bot/SwitchBotDeviceApi.java index 0191862..b70b301 100644 --- a/src/main/java/com/bigboxer23/switch_bot/SwitchBotDeviceApi.java +++ b/src/main/java/com/bigboxer23/switch_bot/SwitchBotDeviceApi.java @@ -6,6 +6,8 @@ import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.util.List; +import java.util.Optional; + import okhttp3.RequestBody; import okhttp3.Response; import org.slf4j.Logger; @@ -65,16 +67,20 @@ public void sendDeviceControlCommands(String deviceId, DeviceCommand command) th } } + /** + * API is a bit weird, and need to check in returned body for status code as well + * + * @param response + * @param clazz + * @return + * @param + * @throws IOException + */ private T parseResponse(Response response, Class clazz) throws IOException { - if (!response.isSuccessful()) { - throw new IOException(response.code() + " " + response.message() + " " - + response.body().string()); - } - String body = response.body().string(); - T apiResponse = provider.getMoshi().adapter(clazz).fromJson(body); - if (!provider.checkForError(apiResponse)) { - throw new IOException(response.code() + " " + response.message() + " " + body); + Optional apiResponse = OkHttpUtil.getBody(response, clazz); + if (apiResponse.isEmpty() || !provider.checkForError(apiResponse.get())) { + throw new IOException(response.code() + " " + response.message()); } - return apiResponse; + return apiResponse.get(); } }