From 74ed7475c9d57b667c1788b8a8d590f1716fb2c7 Mon Sep 17 00:00:00 2001 From: QAIU <736226400@qq.com> Date: Mon, 24 Mar 2025 13:35:40 +0800 Subject: [PATCH] =?UTF-8?q?json=E5=BC=82=E5=B8=B8=E6=97=B6,=20=E5=BF=AB?= =?UTF-8?q?=E9=80=9F=E5=A4=B1=E8=B4=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/main/java/cn/qaiu/parser/PanBase.java | 43 +++++++++++++++++-- 1 file changed, 39 insertions(+), 4 deletions(-) diff --git a/parser/src/main/java/cn/qaiu/parser/PanBase.java b/parser/src/main/java/cn/qaiu/parser/PanBase.java index 9b78552..7742b4b 100644 --- a/parser/src/main/java/cn/qaiu/parser/PanBase.java +++ b/parser/src/main/java/cn/qaiu/parser/PanBase.java @@ -168,9 +168,9 @@ public abstract class PanBase implements IPanTool { * @return JsonObject */ protected JsonObject asJson(HttpResponse res) { + // 检查响应头中的Content-Encoding是否为gzip + String contentEncoding = res.getHeader("Content-Encoding"); try { - // 检查响应头中的Content-Encoding是否为gzip - String contentEncoding = res.getHeader("Content-Encoding"); if ("gzip".equalsIgnoreCase(contentEncoding)) { // 如果是gzip压缩的响应体,解压 return new JsonObject(decompressGzip((Buffer) res.body())); @@ -179,8 +179,43 @@ public abstract class PanBase implements IPanTool { } } catch (Exception e) { - fail("解析失败: json格式异常: {}", res.bodyAsString()); - throw new RuntimeException("解析失败: json格式异常"); + if ("gzip".equalsIgnoreCase(contentEncoding)) { + // 如果是gzip压缩的响应体,解压 + try { + log.error(decompressGzip((Buffer) res.body())); + fail(decompressGzip((Buffer) res.body())); + throw new RuntimeException("响应不是JSON格式"); + } catch (IOException ex) { + log.error("响应gzip解压失败"); + fail("响应gzip解压失败: {}", ex.getMessage()); + throw new RuntimeException("响应gzip解压失败", ex); + } + } else { + log.error("解析失败: json格式异常: {}", res.bodyAsString()); + fail("解析失败: json格式异常: {}", res.bodyAsString()); + throw new RuntimeException("解析失败: json格式异常"); + } + } + } + + /** + * body To text的封装, 会自动处理异常, 会自动解压gzip + * @param res HttpResponse + * @return String + */ + protected String asText(HttpResponse res) { + // 检查响应头中的Content-Encoding是否为gzip + String contentEncoding = res.getHeader("Content-Encoding"); + try { + if ("gzip".equalsIgnoreCase(contentEncoding)) { + // 如果是gzip压缩的响应体,解压 + return decompressGzip((Buffer) res.body()); + } else { + return res.bodyAsString(); + } + } catch (Exception e) { + fail("解析失败: res格式异常"); + throw new RuntimeException("解析失败: res格式异常"); } }