extend CommonRequest for GsonRequest

This commit is contained in:
Timi
2025-07-24 18:46:35 +08:00
parent 91ef5e3bc3
commit 016e0b0962
3 changed files with 22 additions and 10 deletions

View File

@ -32,6 +32,10 @@ public class CommonRequest {
return request.execute().returnContent().asString();
}
public Number asNumber() throws IOException {
return Double.parseDouble(asString());
}
public byte[] asBytes() throws IOException {
return request.execute().returnContent().asBytes();
}

View File

@ -14,16 +14,14 @@ import java.io.IOException;
* @author 夜雨
* @since 2025-07-15 14:27
*/
public class GsonRequest {
public class GsonRequest extends CommonRequest {
private static final Gson GSON = new Gson();
protected final Request request;
private Gson gson = null;
protected GsonRequest(Request request) {
this.request = request;
super(request);
}
protected Gson getGson() {
@ -48,18 +46,18 @@ public class GsonRequest {
}
public <T> T resultAs(Class<T> clazz) throws IOException {
return getGson().fromJson(request.execute().returnContent().asString(), clazz);
return getGson().fromJson(super.asString(), clazz);
}
public <T> T resultAs(TypeToken<T> typeToken) throws IOException {
return getGson().fromJson(request.execute().returnContent().asString(), typeToken);
return getGson().fromJson(super.asString(), typeToken);
}
public JsonObject asJsonObject() throws IOException {
return JsonParser.parseString(request.execute().returnContent().asString()).getAsJsonObject();
return JsonParser.parseString(super.asString()).getAsJsonObject();
}
public JsonArray asJsonArray() throws IOException {
return JsonParser.parseString(request.execute().returnContent().asString()).getAsJsonArray();
return JsonParser.parseString(super.asString()).getAsJsonArray();
}
}

View File

@ -28,8 +28,18 @@ public class TimiRequest extends GsonRequest {
return new TimiRequest(Request.post(url));
}
@Override
public String asString() throws IOException {
return resultAs(String.class);
}
@Override
public Number asNumber() throws IOException {
return Double.parseDouble(asString());
}
public <T> T resultAs(Class<T> clazz) throws IOException {
TimiResponse<T> resp = getGson().fromJson(request.execute().returnContent().asString(), TypeToken.getParameterized(TimiResponse.class, clazz).getType());
TimiResponse<T> resp = getGson().fromJson(asJsonObject(), TypeToken.getParameterized(TimiResponse.class, clazz).getType());
if (resp.isFail()) {
throw resp.toException();
}
@ -37,7 +47,7 @@ public class TimiRequest extends GsonRequest {
}
public <T> T resultAs(TypeToken<T> typeToken) throws IOException {
TimiResponse<T> resp = getGson().fromJson(request.execute().returnContent().asString(), TypeToken.getParameterized(TimiResponse.class, typeToken.getType()).getType());
TimiResponse<T> resp = getGson().fromJson(asJsonObject(), TypeToken.getParameterized(TimiResponse.class, typeToken.getType()).getType());
if (resp.isFail()) {
throw resp.toException();
}