-
Notifications
You must be signed in to change notification settings - Fork 2
feat(common): Add HttpTool #2142
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
Signed-off-by: unknowIfGuestInDream <liang.tang.cx@gmail.com>
|
Thank you for following naming conventions! 😻 |
Reviewer's GuideThis PR introduces File-Level Changes
Assessment against linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
|
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
Their most recently public accepted PR is: #2134 |
|
Warning Rate limit exceeded@unknowIfGuestInDream has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 12 minutes and 51 seconds before requesting another review. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. 📒 Files selected for processing (1)
""" Walkthrough本次变更主要新增了一个基于JavaFX的HTTP接口调试工具,包括前端FXML界面和后端逻辑实现,支持多种HTTP方法、参数、Header和Cookie配置,并能显示响应内容和头部信息。同时,扩展了底层HTTP工具类,支持更多HTTP请求方式,并增加了JSON格式化与压缩等实用方法。相关依赖和资源文件也已同步更新。 Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant HttpTool(UI)
participant HttpUtil
participant RemoteServer
User->>HttpTool(UI): 输入URL、选择方法、配置参数
User->>HttpTool(UI): 点击“发送”
HttpTool(UI)->>HttpUtil: 构建并发送HTTP请求
HttpUtil->>RemoteServer: HTTP请求
RemoteServer-->>HttpUtil: HTTP响应
HttpUtil-->>HttpTool(UI): 返回HttpResponse
HttpTool(UI)-->>User: 展示响应内容与头部信息
Assessment against linked issues
Suggested labels
Suggested reviewers
Poem
✨ Finishing Touches
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hey @unknowIfGuestInDream - I've reviewed your changes - here's some feedback:
HttpUtil.executereturningnullon exceptions can hide the root cause of errors fromHttpTool.HttpToolshould explicitly setContent-Typefor requests with bodies, asHttpUtilno longer defaults it.- Clarify the purpose of new dependencies
org.fxmisc.flowless(forJsonCodeArea) andjdk.httpserver, as their usage byHttpToolis not apparent from the diff.
Here's what I looked at during the review
- 🟡 General issues: 3 issues found
- 🟢 Security: all looks good
- 🟢 Testing: all looks good
- 🟢 Documentation: all looks good
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
Qodana Community for JVMIt seems all right 👌 No new problems were found according to the checks applied 💡 Qodana analysis was run in the pull request mode: only the changed files were checked Contact Qodana teamContact us at qodana-support@jetbrains.com
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 5
🔭 Outside diff range comments (2)
core/src/main/java/com/tlcsdm/core/util/HttpUtil.java (2)
128-144:⚠️ Potential issue默认 UA 覆盖用户自定义 Header,违反最小惊讶原则
buildHeader先写入调用方提供的 Header,随后无条件builder.setHeader("User-Agent", userAgent),会覆盖掉调用方显式设置的 UA。建议:-if (header != null && !header.containsKey("User-Agent")) { - builder.setHeader("User-Agent", userAgent); -} +builder.headers().map(); // no-op, just to illustrate或者在循环前先设置默认 UA,循环时使用
builder.header(key, value)追加而非覆盖。
107-125: 🛠️ Refactor suggestion表单编码遗漏
URLEncoder,且尾随tmp=tmp令人生疑
- 拼装
k=v时未对 k、v 进行 URL 编码。- 结尾追加
tmp=tmp会向服务器发送无效字段,建议删除。
🧹 Nitpick comments (9)
common/src/main/java/module-info.java (1)
57-58: 模块依赖添加合理添加
jdk.httpserver和org.fxmisc.flowless依赖是支持新增的HTTP调试工具所必需的。HTTP服务器模块用于测试功能,flowless模块用于高级UI控件支持。可以考虑将这些依赖标记为静态依赖(如
requires static),如果它们只在特定功能使用时才需要。- requires jdk.httpserver; - requires org.fxmisc.flowless; + requires static jdk.httpserver; + requires static org.fxmisc.flowless;core/src/main/resources/com/tlcsdm/core/static/javafx/richtext/json-keywords.css (1)
1-42: JSON语法高亮样式表设计良好CSS文件定义了JSON语法高亮的样式,为不同的JSON元素(键、值、括号、逗号等)设置了不同的颜色,使JSON内容在UI中更易于阅读和理解。
关于静态分析工具的警告:
-fx-fill属性在JavaFX CSS中是有效的,用于设置文本颜色。这些警告是误报,可以安全忽略。可以考虑添加一些注释说明每种颜色的设计意图,以及可能的暗色主题适配方案。
🧰 Tools
🪛 Biome (1.9.4)
[error] 29-29: Unknown property is not allowed.
See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.(lint/correctness/noUnknownProperty)
[error] 33-33: Unknown property is not allowed.
See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.(lint/correctness/noUnknownProperty)
[error] 37-37: Unknown property is not allowed.
See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.(lint/correctness/noUnknownProperty)
common/src/main/resources/com/tlcsdm/jfxcommon/fxml/httpTool.fxml (1)
1-179: 布局结构清晰,功能完整的HTTP工具UIFXML文件定义了一个功能完善的HTTP调试工具界面,包括:
- 顶部的URL输入和HTTP方法选择
- 左侧的请求参数、请求头和Cookie配置
- 中间区域的响应内容、响应头和图像显示
布局组织良好,ID命名规范,为控制器类提供了清晰的引用点。
建议考虑以下几点改进:
- 添加国际化支持,替换硬编码的中文文本
- 考虑为响应区域添加状态代码和响应时间的显示
- 可能需要添加一个请求体(body)编辑区域,支持POST、PUT等方法
core/src/main/java/com/tlcsdm/core/javafx/richtext/JsonCodeArea.java (2)
40-44: 修复JavaDoc中的拼写错误类注释中有一个拼写错误:"SON Code Area",应该是"JSON Code Area"。
-/** - * SON Code Area - * - * @author unknowIfGuestInDream - */ +/** + * JSON Code Area + * + * @author unknowIfGuestInDream + */
76-94: 高亮计算方法实现高效
computeHighlighting方法使用正则表达式匹配器和StyleSpansBuilder有效地计算并应用样式跨度。代码逻辑清晰,使用了适当的断言确保样式类不为空。可以考虑添加性能优化,对于大型JSON文档,可能需要限制单次处理的文本长度或采用增量处理方法。
common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java (3)
300-304: 仅将 200 视为成功过于严格HTTP 201、202、204、3xx(重定向) 等状态也可能代表正常流程。建议改为
>=200 && <400或让用户决定是否接受重定向/无内容响应。
244-252: 为空 Cookie 仍然插入 Header,可省略若
paramsCookietableData为空,仍然向headerMap写入Cookie: "",可能导致服务器解析异常。可在!paramsCookieBuffer.isEmpty()时再执行headerMap.put(...)。
105-110: 常量应声明为static final提升可读性
methodStrings、paramsDatatableData等不随实例变化,建议:-private String[] methodStrings = new String[]{"GET", "POST", "HEAD", "PUT", "PATCH", "DELETE"}; +private static final String[] METHOD_STRINGS = {"GET", "POST", "HEAD", "PUT", "PATCH", "DELETE"};同时修改引用。
core/src/main/java/com/tlcsdm/core/util/HttpUtil.java (1)
146-151: 每次请求都创建HttpClient,浪费资源并导致连接复用失效
HttpClient线程安全且支持 keep-alive,建议改为单例:-private static HttpResponse<String> execute(HttpRequest.Builder builder, Charset charset) { - var request = builder.build(); - try { - var client = HttpClient.newBuilder().sslContext(SSLContextBuilder.create().build()).build(); +private static final HttpClient CLIENT = + HttpClient.newBuilder() + .sslContext(SSLContextBuilder.create().build()) + .build(); + +private static HttpResponse<String> execute(HttpRequest.Builder builder, Charset charset) { + var request = builder.build(); + try { + var client = CLIENT; return client.send(request, HttpResponse.BodyHandlers.ofString(charset));可进一步设置全局超时、重定向策略等。
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (2)
core/src/main/resources/com/tlcsdm/core/static/icon/http.pngis excluded by!**/*.pngcore/src/main/resources/com/tlcsdm/core/static/icon/http@2x.pngis excluded by!**/*.png
📒 Files selected for processing (10)
common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java(1 hunks)common/src/main/java/com/tlcsdm/jfxcommon/debug/ScanPortTool.java(1 hunks)common/src/main/java/module-info.java(1 hunks)common/src/main/resources/com/tlcsdm/jfxcommon/fxml/httpTool.fxml(1 hunks)core/src/main/java/com/tlcsdm/core/javafx/controlsfx/FxJDKToolActionGroup.java(1 hunks)core/src/main/java/com/tlcsdm/core/javafx/helper/ImageViewHelper.java(1 hunks)core/src/main/java/com/tlcsdm/core/javafx/richtext/JsonCodeArea.java(1 hunks)core/src/main/java/com/tlcsdm/core/util/HttpUtil.java(4 hunks)core/src/main/java/com/tlcsdm/core/util/JacksonUtil.java(2 hunks)core/src/main/resources/com/tlcsdm/core/static/javafx/richtext/json-keywords.css(1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
core/src/main/java/com/tlcsdm/core/util/HttpUtil.java (1)
core/src/main/java/com/tlcsdm/core/javafx/util/OSUtil.java (1)
OSUtil(46-185)
🪛 Biome (1.9.4)
core/src/main/resources/com/tlcsdm/core/static/javafx/richtext/json-keywords.css
[error] 29-29: Unknown property is not allowed.
See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.
(lint/correctness/noUnknownProperty)
[error] 33-33: Unknown property is not allowed.
See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.
(lint/correctness/noUnknownProperty)
[error] 37-37: Unknown property is not allowed.
See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.
(lint/correctness/noUnknownProperty)
🪛 GitHub Check: CodeFactor
common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java
[notice] 223-316: common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java#L223-L316
Complex Method
⏰ Context from checks skipped due to timeout of 90000ms (9)
- GitHub Check: build (21, ubuntu-latest, false)
- GitHub Check: build (17, windows-latest, false)
- GitHub Check: build (21, windows-latest, false)
- GitHub Check: build (21, macos-latest, false)
- GitHub Check: build (17, ubuntu-latest, false)
- GitHub Check: build (17, macos-latest, false)
- GitHub Check: qodana
- GitHub Check: StepSecurity Harden-Runner
- GitHub Check: Summary
🔇 Additional comments (6)
core/src/main/java/com/tlcsdm/core/javafx/controlsfx/FxJDKToolActionGroup.java (1)
99-99: 日志级别调整得当将未找到JDK工具可执行文件的日志级别从warn调整为debug是合理的改动,因为这种情况通常不是错误,而是配置差异导致的正常情况。
core/src/main/java/com/tlcsdm/core/util/JacksonUtil.java (1)
192-206: JSON格式化方法实现合理该方法通过Jackson将JSON解析后重新格式化输出,实现了JSON美化功能。错误处理适当,在解析失败时返回原始字符串。
core/src/main/java/com/tlcsdm/core/javafx/helper/ImageViewHelper.java (1)
83-83: 图标资源添加符合需求为HttpTool添加http图标支持,保持了代码一致性,与新功能匹配。
common/src/main/java/com/tlcsdm/jfxcommon/debug/ScanPortTool.java (1)
341-353: 良好的封装改进!将
setTableColumnMapValueFactory方法从 public 修改为 private 是一个很好的封装改进。这个方法只在类内部使用(在initializeOption方法中),限制其访问范围有助于隐藏实现细节,减少类的公共 API 暴露面。这符合面向对象设计中的信息隐藏原则。core/src/main/java/com/tlcsdm/core/javafx/richtext/JsonCodeArea.java (1)
65-74: 构造函数实现完善构造函数设置了适当的样式类和样式表,并添加了行号显示和文本变化监听器,以便在文本变化时更新语法高亮。这是一个良好的实现,确保了JSON编辑器的核心功能。
core/src/main/java/com/tlcsdm/core/util/HttpUtil.java (1)
70-93: 新增 PUT/PATCH 请求体的Content-Type未明确
doPut/doPatch接收字符串 body,但未设置Content-Type,服务器可能无法正确解析。可与doPostForm类似增加参数或默认值(如application/json或application/x-www-form-urlencoded)。
Signed-off-by: unknowIfGuestInDream <liang.tang.cx@gmail.com>
Signed-off-by: unknowIfGuestInDream <liang.tang.cx@gmail.com>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 3
♻️ Duplicate comments (4)
common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java (4)
260-273:⚠️ Potential issueGET请求参数未进行URL编码
直接拼接参数可能导致特殊字符(如空格、&、=、中文等)产生错误的URL。建议对参数名和值进行URL编码。
- paramsMap.forEach((key, value) -> paramsDataBuffer.append(key).append("=").append(value).append("&")); + paramsMap.forEach((key, value) -> { + try { + paramsDataBuffer.append(URLEncoder.encode(key, StandardCharsets.UTF_8.toString())) + .append("=") + .append(URLEncoder.encode(value, StandardCharsets.UTF_8.toString())) + .append("&"); + } catch (UnsupportedEncodingException e) { + StaticLog.error(e, "URL编码错误"); + paramsDataBuffer.append(key).append("=").append(value).append("&"); + } + });并添加相应的导入语句:
import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.net.URLEncoder;
282-291:⚠️ Potential issuePOST请求参数未进行URL编码
与GET请求类似,POST请求体的参数也需要进行URL编码,特别是在使用表单格式(application/x-www-form-urlencoded)时。
建议添加辅助方法进行参数编码,如:
private String encodeParameters(String input) { if (input == null || input.isEmpty()) { return input; } StringBuilder result = new StringBuilder(); String[] params = input.split("&"); for (String param : params) { int idx = param.indexOf("="); if (idx > 0) { String key = param.substring(0, idx); String value = param.substring(idx + 1); try { String encodedValue = URLEncoder.encode(value, StandardCharsets.UTF_8.toString()); result.append(key).append("=").append(encodedValue).append("&"); } catch (Exception e) { // 异常情况下使用原始值 result.append(param).append("&"); } } else { result.append(param).append("&"); } } if (result.length() > 0) { result.setLength(result.length() - 1); } return result.toString(); }然后修改POST请求部分:
- response = HttpUtil.doPost(url, headerMap, body); + response = HttpUtil.doPost(url, headerMap, encodeParameters(body));
227-326: 🛠️ Refactor suggestion方法体过长且职责过多
当前
sendAction方法超过100行,包含多种职责(输入校验、请求构建、网络请求、响应处理等),可维护性差且难以测试。建议拆分为多个职责单一的方法:
validateInput()- 负责验证用户输入buildRequestParams()- 构建请求参数、头部和CookieexecuteRequest()- 根据HTTP方法执行请求processResponse()- 处理响应并更新UI例如:
@FXML private void sendAction(ActionEvent event) { String url = urlTextField.getText().trim(); if (!validateInput(url)) { return; } RequestParams params = buildRequestParams(); executeRequestAsync(url, params); } private boolean validateInput(String url) { if (StringUtils.isEmpty(url)) { notificationBuilder.text("请输入网站!!!"); notificationBuilder.showWarning(); return false; } return true; } private RequestParams buildRequestParams() { // 构建参数、头部和Cookie的代码... } private void executeRequestAsync(String url, RequestParams params) { // 使用后台线程执行请求 new Thread(() -> { HttpResponse<String> response = null; try { response = executeRequest(url, params); Platform.runLater(() -> processResponse(response)); } catch (Exception e) { Platform.runLater(() -> { notificationBuilder.text("请求失败: " + e.getMessage()); notificationBuilder.showError(); }); } }).start(); }🧰 Tools
🪛 GitHub Check: CodeFactor
[notice] 227-326: common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java#L227-L326
Complex Method
260-301: 🛠️ Refactor suggestion网络请求阻塞UI线程
当前直接在JavaFX Application Thread上执行HTTP请求,这会导致界面在请求期间冻结,影响用户体验。
建议使用异步方式执行请求:
// 使用CompletableFuture或Task CompletableFuture.supplyAsync(() -> { // 执行HTTP请求... return HttpUtil.doGet(url, headerMap); }).whenComplete((response, exception) -> { Platform.runLater(() -> { if (exception != null) { notificationBuilder.text("请求失败: " + exception.getMessage()); notificationBuilder.showError(); } else { // 处理响应... processResponse(response); } }); });或者使用JavaFX的Task类:
Task<HttpResponse<String>> task = new Task<>() { @Override protected HttpResponse<String> call() throws Exception { return HttpUtil.doGet(url, headerMap); } }; task.setOnSucceeded(e -> { HttpResponse<String> response = task.getValue(); processResponse(response); }); task.setOnFailed(e -> { notificationBuilder.text("请求失败: " + task.getException().getMessage()); notificationBuilder.showError(); }); new Thread(task).start();
🧹 Nitpick comments (8)
core/src/main/resources/com/tlcsdm/core/static/javafx/richtext/json-keywords.css (1)
1-26: 许可证和版权信息代码中的许可证日期(2025年)似乎是未来日期,可能需要更新为当前年份。
-/* - * Copyright (c) 2025 unknowIfGuestInDream. - * All rights reserved. +/* + * Copyright (c) 2023 unknowIfGuestInDream. + * All rights reserved.common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java (7)
192-203: 使用匿名内部类实现监听器当前代码使用了匿名内部类实现
ChangeListener,可以使用Lambda表达式简化代码。- paramsDataIsStringCheckBox.selectedProperty().addListener(new ChangeListener<Boolean>() { - @Override - public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { - if (newValue) { - paramsDataTextArea.setVisible(true); - paramsDataTableView.setVisible(false); - } else { - paramsDataTextArea.setVisible(false); - paramsDataTableView.setVisible(true); - } - } - }); + paramsDataIsStringCheckBox.selectedProperty().addListener((observable, oldValue, newValue) -> { + paramsDataTextArea.setVisible(newValue); + paramsDataTableView.setVisible(!newValue); + });
92-96: 组件命名不一致
ResponseBodyTextArea和ResponseHeaderTextArea组件使用了大写驼峰命名,而其他组件如urlTextField使用小写驼峰命名。应当保持一致的命名风格。- @FXML - private JsonCodeArea ResponseBodyTextArea; - @FXML - private InformationArea ResponseHeaderTextArea; + @FXML + private JsonCodeArea responseBodyTextArea; + @FXML + private InformationArea responseHeaderTextArea;同时需要更新所有引用这些组件的地方,如第210、216、223、320、324行。
345-347: 在toBrowerAction方法中缺少错误提示当URL为空时,该方法静默返回,没有向用户提供反馈。应该添加警告通知。
if (url.isEmpty()) { + notificationBuilder.text("请输入有效的URL"); + notificationBuilder.showWarning(); return; }
351-354: 泛型类型安全性问题
setTableColumnMapValueFactory方法中的TableColumn参数缺少泛型类型声明,导致使用了原始类型,可能引起类型安全问题。- private void setTableColumnMapValueFactory(TableColumn tableColumn, String name) { + private void setTableColumnMapValueFactory(TableColumn<Map<String, String>, String> tableColumn, String name) {
185-191: 未使用的注释代码初始化UI方法中包含已注释掉的代码,这些代码可能是开发过程中的遗留物。应当移除这些无用代码以保持代码整洁。
- // JsonCodeArea area = new JsonCodeArea(); - // area.setEditable(false); - // area.appendText( - // FileUtil.readUtf8String(FileUtil.file(ConfigureUtil.getConfigurePath(Config.CONFIG_FILE_NAME)))); - //VirtualizedScrollPane<JsonCodeArea> pane = new VirtualizedScrollPane<>();
158-166: 初始化方法缺少对未成功初始化的处理
initialize方法调用了多个初始化辅助方法,但没有捕获或处理这些方法可能抛出的异常。如果初始化过程中出现问题,可能导致应用程序状态不一致。添加异常处理:
@FXML public void initialize() { + try { initializeOption(); initializeUI(); initializeUserDataBindings(); initializeBindings(); initializeUserData(); + } catch (Exception e) { + StaticLog.error(e, "初始化HTTP工具失败"); + notificationBuilder.text("初始化失败:" + e.getMessage()); + notificationBuilder.showError(); + } }
70-74: 缺少导包代码中使用了
HttpResponse和HttpHeaders类,但缺少相应的导入语句。虽然第69-70行有导入,但没有指定具体的包,建议使用明确的导入路径。- import java.net.http.HttpHeaders; - import java.net.http.HttpResponse; + import java.net.http.HttpHeaders; + import java.net.http.HttpResponse;
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (6)
common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java(1 hunks)common/src/main/java/module-info.java(1 hunks)common/src/main/resources/com/tlcsdm/jfxcommon/fxml/httpTool.fxml(1 hunks)core/src/main/java/com/tlcsdm/core/javafx/richtext/InformationArea.java(1 hunks)core/src/main/java/com/tlcsdm/core/javafx/richtext/JsonCodeArea.java(1 hunks)core/src/main/resources/com/tlcsdm/core/static/javafx/richtext/json-keywords.css(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
- common/src/main/java/module-info.java
- core/src/main/java/com/tlcsdm/core/javafx/richtext/JsonCodeArea.java
- common/src/main/resources/com/tlcsdm/jfxcommon/fxml/httpTool.fxml
🧰 Additional context used
🪛 GitHub Check: CodeFactor
common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java
[notice] 227-326: common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java#L227-L326
Complex Method
🪛 Biome (1.9.4)
core/src/main/resources/com/tlcsdm/core/static/javafx/richtext/json-keywords.css
[error] 29-29: Unknown property is not allowed.
See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.
(lint/correctness/noUnknownProperty)
[error] 30-30: Unknown property is not allowed.
See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.
(lint/correctness/noUnknownProperty)
[error] 34-34: Unknown property is not allowed.
See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.
(lint/correctness/noUnknownProperty)
[error] 35-38: Unknown property is not allowed.
See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.
(lint/correctness/noUnknownProperty)
[error] 39-39: Unknown property is not allowed.
See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.
(lint/correctness/noUnknownProperty)
⏰ Context from checks skipped due to timeout of 90000ms (9)
- GitHub Check: build (21, macos-latest, false)
- GitHub Check: build (21, windows-latest, false)
- GitHub Check: build (17, windows-latest, false)
- GitHub Check: build (21, ubuntu-latest, false)
- GitHub Check: build (17, ubuntu-latest, false)
- GitHub Check: build (17, macos-latest, false)
- GitHub Check: qodana
- GitHub Check: StepSecurity Harden-Runner
- GitHub Check: Summary
🔇 Additional comments (3)
core/src/main/java/com/tlcsdm/core/javafx/richtext/InformationArea.java (1)
71-73: 添加了简便的文本设置方法
setText方法增强了 InformationArea 组件的易用性,通过封装replaceText操作提供了更直观的接口。这与文档中提到的JsonCodeArea类的setText方法形成了一致的 API 设计。core/src/main/resources/com/tlcsdm/core/static/javafx/richtext/json-keywords.css (1)
28-44: JSON语法高亮样式规则CSS样式规则定义合理,为JSON不同元素(键、值、括号等)提供了良好的视觉区分。建议考虑添加注释的英文翻译,以便非中文开发者理解。
另外,
-fx-fill和-fx-font-weight属性是JavaFX特有的CSS扩展,某些CSS验证工具可能将其标记为错误,但在JavaFX环境中这些是有效的样式属性。🧰 Tools
🪛 Biome (1.9.4)
[error] 29-29: Unknown property is not allowed.
See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.(lint/correctness/noUnknownProperty)
[error] 30-30: Unknown property is not allowed.
See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.(lint/correctness/noUnknownProperty)
[error] 34-34: Unknown property is not allowed.
See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.(lint/correctness/noUnknownProperty)
[error] 35-38: Unknown property is not allowed.
See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.(lint/correctness/noUnknownProperty)
[error] 39-39: Unknown property is not allowed.
See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.(lint/correctness/noUnknownProperty)
common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java (1)
158-166:❌ Incorrect review comment
未找到
initializeUserDataBindings、initializeBindings和initializeUserData的实现
initialize方法调用了三个未在类中实现的方法:initializeUserDataBindings、initializeBindings和initializeUserData。这可能导致运行时错误。如果这些方法应该被实现但尚未完成,请完成它们的实现;如果它们由父类提供,请确保它们能够适用于当前类。
🏁 Script executed:
#!/bin/bash # 检查这些方法是否在父类中存在 grep -r "initializeUserDataBindings\|initializeBindings\|initializeUserData" --include="*.java" .Length of output: 11136
🏁 Script executed:
#!/bin/bash # 检查 HttpTool 类的声明和继承关系 sed -n '1,50p' common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java rg "extends" -n common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.javaLength of output: 2829
🏁 Script executed:
#!/bin/bash # 查看 CommonSample 类及其方法定义 sed -n '1,200p' common/src/main/java/com/tlcsdm/jfxcommon/CommonSample.java # 查找关键方法在 CommonSample 中的声明 rg -n "initializeBindings" common/src/main/java/com/tlcsdm/jfxcommon/CommonSample.java rg -n "initializeUserDataBindings" common/src/main/java/com/tlcsdm/jfxcommon/CommonSample.java rg -n "initializeUserData" common/src/main/java/com/tlcsdm/jfxcommon/CommonSample.javaLength of output: 2287
方法已在父类 SampleBase 中实现,无需在 HttpTool 中重复声明
initializeUserDataBindings、initializeBindings和initializeUserData这三个方法均由com.tlcsdm.frame.SampleBase提供,HttpTool通过继承CommonSample(又继承自SampleBase)可以直接使用父类实现,不会引发运行时错误。请忽略先前关于“未找到这些方法实现”的评论。
Likely an incorrect or invalid review comment.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
♻️ Duplicate comments (6)
common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java (6)
258-272:⚠️ Potential issueGET请求参数未经URL编码
当前代码直接将参数拼接到URL中,未进行URL编码,这可能导致请求失败或安全问题。
请对参数进行URL编码:
- paramsMap.forEach((key, value) -> paramsDataBuffer.append(key).append("=").append(value).append("&")); + paramsMap.forEach((key, value) -> { + try { + paramsDataBuffer.append(URLEncoder.encode(key, StandardCharsets.UTF_8)) + .append("=") + .append(URLEncoder.encode(value, StandardCharsets.UTF_8)) + .append("&"); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException("编码不支持", e); + } + });同时需要添加导入:
import java.net.URLEncoder; import java.nio.charset.StandardCharsets;
281-290:⚠️ Potential issuePOST请求参数未经URL编码
POST请求的参数体构建没有进行URL编码,可能导致特殊字符处理错误。
请对表单参数进行URL编码:
- response = HttpUtil.doPost(url, headerMap, body); + response = HttpUtil.doPost(url, headerMap, encodeParameters(body));并添加辅助方法:
private String encodeParameters(String input) { if (input == null || input.isEmpty()) { return input; } StringBuilder result = new StringBuilder(); String[] params = input.split("&"); for (String param : params) { int idx = param.indexOf("="); if (idx > 0) { String key = param.substring(0, idx); String value = param.substring(idx + 1); try { String encodedValue = URLEncoder.encode(value, StandardCharsets.UTF_8.toString()); result.append(key).append("=").append(encodedValue).append("&"); } catch (Exception e) { // 异常情况下使用原始值 result.append(param).append("&"); } } else { result.append(param).append("&"); } } // 移除末尾的'&' if (result.length() > 0) { result.setLength(result.length() - 1); } return result.toString(); }
302-306: 🛠️ Refactor suggestionHTTP状态码处理过于严格
当前代码只将状态码200视为成功,忽略了其他有效的2xx状态码(如201、202、204等)。
修改状态码检查逻辑:
- if (response == null || response.statusCode() != 200) { + if (response == null) { notificationBuilder.text("请求失败"); notificationBuilder.showError(); return; } + if (response.statusCode() < 200 || response.statusCode() >= 300) { + notificationBuilder.text("请求失败,状态码:" + response.statusCode()); + notificationBuilder.showWarning(); + // 继续处理响应,显示错误信息 + }
258-300: 🛠️ Refactor suggestion在UI线程中执行网络请求
当前代码直接在JavaFX Application Thread中执行HTTP请求,这会导致UI冻结,影响用户体验。
建议在后台线程中执行HTTP请求:
CompletableFuture.supplyAsync(() -> { // 执行HTTP请求的代码 HttpResponse<String> response = null; if ("GET".equals(methodString)) { // GET请求逻辑... } else if ("POST".equals(methodString)) { // POST请求逻辑... } // 其他请求类型... return response; }).whenCompleteAsync((response, exception) -> { Platform.runLater(() -> { if (exception != null) { notificationBuilder.text("请求异常: " + exception.getMessage()); notificationBuilder.showError(); } else if (response == null) { notificationBuilder.text("请求失败"); notificationBuilder.showError(); } else { // 处理响应... renderResponse(response); } }); });需要添加导入:
import java.util.concurrent.CompletableFuture; import javafx.application.Platform;
314-316:⚠️ Potential issue响应头处理存在错误
代码错误地删除了响应头字符串缓冲区的第一个字符,这可能导致第一个响应头的首字符丢失。
移除不正确的字符删除逻辑:
- if (!headerStringBuffer.isEmpty()) { - headerStringBuffer.deleteCharAt(0); - }如果目的是移除末尾多余的换行符,应该修改为:
if (headerStringBuffer.length() > 0 && headerStringBuffer.charAt(headerStringBuffer.length() - 1) == '\n') { headerStringBuffer.deleteCharAt(headerStringBuffer.length() - 1); }
132-133:⚠️ Potential issue国际化资源键不正确
当前使用的国际化资源键指向端口扫描工具(
scanPortTool),而非HTTP工具。请更新资源键为HTTP工具对应的键:
- return I18nUtils.get("common.tool.debug.scanPortTool.sampleDesc"); + return I18nUtils.get("common.tool.debug.httpTool.sampleDesc");同时确保在国际化资源文件中添加了对应的键值对。
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java(1 hunks)core/src/main/java/com/tlcsdm/core/util/DependencyUtil.java(1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
core/src/main/java/com/tlcsdm/core/util/DependencyUtil.java (1)
core/src/main/java/com/tlcsdm/core/util/CoreUtil.java (1)
CoreUtil(58-303)
🪛 GitHub Check: CodeFactor
common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java
[notice] 226-325: common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java#L226-L325
Complex Method
⏰ Context from checks skipped due to timeout of 90000ms (9)
- GitHub Check: qodana
- GitHub Check: build (17, windows-latest, false)
- GitHub Check: build (21, windows-latest, false)
- GitHub Check: build (21, macos-latest, false)
- GitHub Check: build (21, ubuntu-latest, false)
- GitHub Check: build (17, ubuntu-latest, false)
- GitHub Check: build (17, macos-latest, false)
- GitHub Check: StepSecurity Harden-Runner
- GitHub Check: Summary
🔇 Additional comments (20)
core/src/main/java/com/tlcsdm/core/util/DependencyUtil.java (13)
41-46: 修复了中文注释中的错字你修正了方法注释中的"因否存在"为"是否存在",这提高了代码的可读性和专业性。
48-53: 修复了中文注释中的错字你修正了方法注释中的"因否存在"为"是否存在",这提高了代码的可读性和专业性。
55-60: 修复了中文注释中的错字你修正了方法注释中的"因否存在"为"是否存在",这提高了代码的可读性和专业性。
62-67: 修复了中文注释中的错字你修正了方法注释中的"因否存在"为"是否存在",这提高了代码的可读性和专业性。
69-74: 修复了中文注释中的错字你修正了方法注释中的"因否存在"为"是否存在",这提高了代码的可读性和专业性。
76-81: 修复了中文注释中的错字你修正了方法注释中的"因否存在"为"是否存在",这提高了代码的可读性和专业性。
83-88: 修复了中文注释中的错字你修正了方法注释中的"因否存在"为"是否存在",这提高了代码的可读性和专业性。
90-95: 修复了中文注释中的错字你修正了方法注释中的"因否存在"为"是否存在",这提高了代码的可读性和专业性。
97-102: 修复了中文注释中的错字你修正了方法注释中的"因否存在"为"是否存在",这提高了代码的可读性和专业性。
104-109: 修复了中文注释中的错字你修正了方法注释中的"因否存在"为"是否存在",这提高了代码的可读性和专业性。
111-116: 修复了中文注释中的错字你修正了方法注释中的"因否存在"为"是否存在",这提高了代码的可读性和专业性。
118-123: 修复了中文注释中的错字你修正了方法注释中的"因否存在"为"是否存在",这提高了代码的可读性和专业性。
125-130: 添加了对RichTextFX依赖的检测方法该方法检测是否存在RichTextFX库,通过验证
org.fxmisc.richtext.CodeArea类的存在性,这与PR中引入的HttpTool功能相关联。实现简洁且与类中的其他方法保持一致。common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java (7)
1-80: HTTP调试工具类的实现代码实现了一个基于JavaFX的HTTP调试工具,包括了必要的导入和类定义。类继承自CommonSample,并添加了必要的注释和版权信息。
82-114: UI组件定义定义了各种UI组件用于HTTP请求的构建和显示,包括URL输入、方法选择、参数/头部/Cookie表格等。组织结构清晰,变量命名合理。
158-161: 根据RichTextFX依赖判断工具可见性通过
DependencyUtil.hasRichTextFX()判断工具的可见性,这是一个很好的做法,确保只在必要的依赖存在时才显示此工具。这与新增的hasRichTextFX()方法相匹配。
173-188: UI初始化方法实现初始化选项和表格列的实现良好,代码结构清晰,复用了设置表格列映射的逻辑。
190-224: UI事件和上下文菜单设置添加了参数输入方式切换的监听器,设置了表格右键菜单,以及JSON格式化和压缩功能。很好地利用了依赖检测来有条件地添加JSON处理功能。
326-348: UI操作方法实现添加参数行和浏览器打开功能的方法实现简洁明了,逻辑正确。
350-379: 表格辅助方法实现表格列设置和右键菜单事件处理的实现良好,代码结构清晰,功能完整。
Signed-off-by: unknowIfGuestInDream <liang.tang.cx@gmail.com>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 3
♻️ Duplicate comments (5)
common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java (5)
132-135: 资源键引用错误此方法使用了与
ScanPortTool工具相关的国际化资源键,而不是适用于HttpTool的正确键:- return I18nUtils.get("common.tool.debug.scanPortTool.sampleDesc"); + return I18nUtils.get("common.tool.debug.httpTool.sampleDesc");请确保在国际化资源文件中添加与HttpTool相对应的描述文本。
228-330: sendAction方法过于复杂,需要重构该方法承担了多项职责(输入验证、参数构建、请求发送、响应处理等),总计超过100行代码,难以维护和测试。应将其拆分为多个职责单一的小方法:
validateInput()- 验证URL输入buildRequestParams()- 构建请求参数和头信息executeRequest()- 执行HTTP请求processResponse()- 处理响应结果并更新UI这种改进将使代码更易于维护、测试和理解。
🧰 Tools
🪛 GitHub Check: CodeFactor
[notice] 228-331: common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java#L228-L331
Complex Method
280-295: 非GET请求参数未进行URL编码构建非GET请求体时没有对参数值进行URL编码,这可能导致特殊字符问题。请对参数值进行编码:
StringBuilder sb = new StringBuilder(); for (Map<String, String> map : paramsDatatableData) { - sb.append(map.get("name")); - sb.append("="); - sb.append(map.get("value")); + sb.append(URLEncoder.encode(map.get("name"), StandardCharsets.UTF_8)); + sb.append("="); + sb.append(URLEncoder.encode(map.get("value"), StandardCharsets.UTF_8)); sb.append("&"); } String body = sb.toString();同样,POST请求时应对参数进行编码:
- response = HttpUtil.doPost(url, headerMap, body); + response = HttpUtil.doPost(url, headerMap, encodeParameters(body));并添加一个编码辅助方法:
private String encodeParameters(String input) { if (input == null || input.isEmpty()) { return input; } // 如参数已URL编码,则直接返回 if (input.contains("%")) { return input; } StringBuilder result = new StringBuilder(); for (String param : input.split("&")) { if (param.isEmpty()) continue; int idx = param.indexOf("="); if (idx > 0) { String key = param.substring(0, idx); String value = param.substring(idx + 1); result.append(key).append("=") .append(URLEncoder.encode(value, StandardCharsets.UTF_8)) .append("&"); } else { result.append(param).append("&"); } } if (result.length() > 0) { result.setLength(result.length() - 1); } return result.toString(); }
308-312: HTTP状态码处理过于严格当前代码仅将状态码200视为成功,忽略了其他有效的2xx状态码(如201、202、204等)。即使状态码不是2xx,响应头和体仍可能包含有用信息:
- if (response == null || response.statusCode() != 200) { + if (response == null) { notificationBuilder.text("请求失败"); notificationBuilder.showError(); return; } + // 处理非2xx状态码,但仍显示响应信息 + if (response.statusCode() < 200 || response.statusCode() >= 300) { + notificationBuilder.text("请求返回状态码:" + response.statusCode()); + notificationBuilder.showWarning(); + // 继续处理响应,不要直接返回 + }这样做可以在非成功状态下仍然显示服务器返回的错误信息,对调试更友好。
320-322: 响应头处理逻辑错误当前代码错误地删除了响应头字符串的第一个字符,这会导致第一个响应头名称的首字符被删除:
- if (!headerStringBuffer.isEmpty()) { - headerStringBuffer.deleteCharAt(0); - }此代码可能是误将删除最后一个字符(如分隔符)的逻辑写成了删除第一个字符。如果目的是移除最后的换行符,应改为:
if (headerStringBuffer.length() > 0 && headerStringBuffer.charAt(headerStringBuffer.length() - 1) == '\n') { headerStringBuffer.deleteCharAt(headerStringBuffer.length() - 1); }或者,如果不需要删除任何字符,可以直接删除这段代码。
🧹 Nitpick comments (3)
common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java (3)
260-305: 使用策略模式或枚举映射替代冗长的条件判断当前使用了大量if-else语句处理不同HTTP方法,可以改用更优雅的解决方案:
- if ("GET".equals(methodString)) { - // GET实现 - } else { - // 其他方法实现 - if ("POST".equals(methodString)) { - // POST实现 - } else if ("HEAD".equals(methodString)) { - // HEAD实现 - } else if ("PUT".equals(methodString)) { - // PUT实现 - } // 更多条件... - } + // 策略模式或者枚举映射实现 + Map<String, HttpRequestHandler> requestHandlers = Map.of( + "GET", this::handleGetRequest, + "POST", this::handlePostRequest, + "HEAD", this::handleHeadRequest, + "PUT", this::handlePutRequest, + "PATCH", this::handlePatchRequest, + "DELETE", this::handleDeleteRequest + ); + + HttpResponse<String> response = requestHandlers.getOrDefault(methodString, this::handleDefaultRequest).execute(url, headerMap, paramsMap);这样可以避免复杂的条件判断,使代码更易于扩展和维护。
192-204: 使用JavaFX绑定简化UI状态控制当前使用了监听器来控制参数UI的可见性,可以使用JavaFX的绑定功能使代码更简洁:
- paramsDataIsStringCheckBox.selectedProperty().addListener(new ChangeListener<Boolean>() { - @Override - public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { - if (newValue) { - paramsDataTextArea.setVisible(true); - paramsDataTableView.setVisible(false); - } else { - paramsDataTextArea.setVisible(false); - paramsDataTableView.setVisible(true); - } - } - }); + // 使用绑定表达式直接控制UI元素可见性 + paramsDataTextArea.visibleProperty().bind(paramsDataIsStringCheckBox.selectedProperty()); + paramsDataTableView.visibleProperty().bind(paramsDataIsStringCheckBox.selectedProperty().not());这样写更符合JavaFX的声明式风格,代码更简洁且易于维护。
366-385: TableView右键菜单应在初始化时创建,而非每次点击时创建当前代码在每次右键点击时都创建新的ContextMenu,这不仅效率低,还可能导致内存泄漏:
- paramsDataTableView.setOnMouseClicked(event -> { - if (event.getButton() == MouseButton.SECONDARY && !paramsDatatableData.isEmpty()) { - MenuItem menu_Copy = new MenuItem("复制选中行"); - menu_Copy.setOnAction(event1 -> { - Map<String, String> tableBean = paramsDataTableView.getSelectionModel().getSelectedItem(); - Map<String, String> tableBean2 = new HashMap<>(tableBean); - paramsDatatableData.add(paramsDataTableView.getSelectionModel().getSelectedIndex(), tableBean2); - }); - MenuItem menu_Remove = new MenuItem("删除选中行"); - menu_Remove.setOnAction(event1 -> { - paramsDatatableData.remove(paramsDataTableView.getSelectionModel().getSelectedIndex()); - }); - MenuItem menu_RemoveAll = new MenuItem("删除所有"); - menu_RemoveAll.setOnAction(event1 -> { - paramsDatatableData.clear(); - }); - paramsDataTableView.setContextMenu(new ContextMenu(menu_Copy, menu_Remove, menu_RemoveAll)); - } - }); + // 创建上下文菜单及菜单项 + MenuItem menu_Copy = new MenuItem("复制选中行"); + menu_Copy.setOnAction(event1 -> { + if (paramsDataTableView.getSelectionModel().getSelectedItem() != null) { + Map<String, String> tableBean = paramsDataTableView.getSelectionModel().getSelectedItem(); + Map<String, String> tableBean2 = new HashMap<>(tableBean); + paramsDatatableData.add(paramsDataTableView.getSelectionModel().getSelectedIndex(), tableBean2); + } + }); + + MenuItem menu_Remove = new MenuItem("删除选中行"); + menu_Remove.setOnAction(event1 -> { + if (paramsDataTableView.getSelectionModel().getSelectedIndex() >= 0) { + paramsDatatableData.remove(paramsDataTableView.getSelectionModel().getSelectedIndex()); + } + }); + + MenuItem menu_RemoveAll = new MenuItem("删除所有"); + menu_RemoveAll.setOnAction(event1 -> { + paramsDatatableData.clear(); + }); + + ContextMenu contextMenu = new ContextMenu(menu_Copy, menu_Remove, menu_RemoveAll); + + // 根据数据集状态动态控制菜单可用性 + paramsDataTableView.setOnContextMenuRequested(event -> { + boolean hasItems = !paramsDatatableData.isEmpty(); + boolean hasSelection = paramsDataTableView.getSelectionModel().getSelectedItem() != null; + + menu_Copy.setDisable(!hasSelection); + menu_Remove.setDisable(!hasSelection); + menu_RemoveAll.setDisable(!hasItems); + + if (hasItems) { + contextMenu.show(paramsDataTableView, event.getScreenX(), event.getScreenY()); + } + }); + + paramsDataTableView.setContextMenu(contextMenu);这种方式更高效、更符合JavaFX的设计模式,并能更好地处理菜单项的启用/禁用状态。
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java(1 hunks)core/src/main/java/com/tlcsdm/core/javafx/richtext/JsonCodeArea.java(1 hunks)core/src/main/java/com/tlcsdm/core/util/JacksonUtil.java(2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- core/src/main/java/com/tlcsdm/core/util/JacksonUtil.java
- core/src/main/java/com/tlcsdm/core/javafx/richtext/JsonCodeArea.java
🧰 Additional context used
🪛 GitHub Check: CodeFactor
common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java
[notice] 228-331: common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java#L228-L331
Complex Method
⏰ Context from checks skipped due to timeout of 90000ms (9)
- GitHub Check: build (21, windows-latest, false)
- GitHub Check: build (21, macos-latest, false)
- GitHub Check: build (17, macos-latest, false)
- GitHub Check: build (21, ubuntu-latest, false)
- GitHub Check: build (17, windows-latest, false)
- GitHub Check: build (17, ubuntu-latest, false)
- GitHub Check: qodana
- GitHub Check: StepSecurity Harden-Runner
- GitHub Check: Summary
Signed-off-by: unknowIfGuestInDream <liang.tang.cx@gmail.com>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (3)
core/src/main/java/com/tlcsdm/core/util/HttpUtil.java (3)
51-52: 改进GET请求方法返回类型并添加超时设置将doGet方法返回类型从String改为HttpResponse,提供更完整的响应信息(包括状态码、头信息等),并统一添加了10秒超时设置。
考虑将超时时间作为可配置参数,以便应对不同网络环境或大型数据传输场景:
-public static HttpResponse<String> doGet(String url, Map<String, String> header) { - var builder = HttpRequest.newBuilder().uri(URI.create(url)).timeout(Duration.ofSeconds(10)).GET(); +public static HttpResponse<String> doGet(String url, Map<String, String> header) { + return doGet(url, header, 10); +} + +public static HttpResponse<String> doGet(String url, Map<String, String> header, int timeoutSeconds) { + var builder = HttpRequest.newBuilder().uri(URI.create(url)).timeout(Duration.ofSeconds(timeoutSeconds)).GET();
137-147: 优化:基于操作系统动态设置User-Agent根据不同操作系统(Windows、Mac、Linux)设置对应的User-Agent,使HTTP请求更符合真实环境。
建议对所有操作系统情况进行明确处理,包括WINDOWS和UNKNOWN情况:
String userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36 Edg/105.0.1343.50"; switch (OSUtil.getOS()) { + case WINDOWS: + userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36 Edg/105.0.1343.50"; + break; case MAC: userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36"; break; case LINUX: userAgent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36"; break; + case UNKNOWN: + // 使用默认Windows User-Agent或创建通用User-Agent + break; }
149-154: 改进execute方法返回完整的HTTP响应将execute方法更新为直接返回HttpResponse对象,而不是之前只返回响应体内容,提供了更完整的HTTP响应信息。
当发生异常时,方法返回null但没有相关文档说明,这可能导致调用方出现NullPointerException。建议添加注释说明可能返回null的情况,或者考虑使用Optional包装返回值:
-private static HttpResponse<String> execute(HttpRequest.Builder builder, Charset charset) { +/** + * 执行HTTP请求并返回响应 + * + * @param builder 请求构建器 + * @param charset 字符集 + * @return HTTP响应对象,如果发生异常则返回null + */ +private static HttpResponse<String> execute(HttpRequest.Builder builder, Charset charset) {
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
core/src/main/java/com/tlcsdm/core/util/HttpUtil.java(3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
core/src/main/java/com/tlcsdm/core/util/HttpUtil.java (1)
core/src/main/java/com/tlcsdm/core/javafx/util/OSUtil.java (1)
OSUtil(46-185)
⏰ Context from checks skipped due to timeout of 90000ms (9)
- GitHub Check: build (21, windows-latest, false)
- GitHub Check: build (17, windows-latest, false)
- GitHub Check: build (21, ubuntu-latest, false)
- GitHub Check: build (21, macos-latest, false)
- GitHub Check: build (17, ubuntu-latest, false)
- GitHub Check: build (17, macos-latest, false)
- GitHub Check: qodana
- GitHub Check: StepSecurity Harden-Runner
- GitHub Check: Summary
🔇 Additional comments (8)
core/src/main/java/com/tlcsdm/core/util/HttpUtil.java (8)
32-32: 添加OSUtil导入以支持多平台User-Agent设置为了支持根据不同操作系统设置对应的User-Agent,这里添加了OSUtil类的导入。
40-40: 导入Duration类以支持超时设置添加java.time.Duration导入用于为HTTP请求设置超时时间,这是一个很好的改进。
60-65: 改进POST请求方法返回类型并添加超时设置将doPost方法返回类型从String改为HttpResponse,并统一添加了10秒超时设置,使API更一致且信息更完整。
67-75: 添加PUT请求支持新增doPut方法实现PUT请求支持,遵循了与其他HTTP方法一致的编码风格和接口设计,包括10秒超时设置。
77-84: 添加DELETE请求支持新增doDelete方法实现DELETE请求支持,结构清晰简洁,与GET方法类似(无需请求体)。
86-95: 添加PATCH请求支持新增doPatch方法实现PATCH请求支持,使用method()方法显式指定HTTP方法类型,实现逻辑完整。
97-105: 添加HEAD请求支持新增doHead方法实现HEAD请求支持,使用noBody()表示无请求体,符合HEAD请求的规范。
110-110: 更新表单POST请求返回类型将doPostForm方法返回类型从String改为HttpResponse,保持与其他HTTP方法的一致性。
Signed-off-by: unknowIfGuestInDream <liang.tang.cx@gmail.com>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (1)
core/src/main/resources/com/tlcsdm/core/static/javafx/richtext/json-keywords.css (1)
45-45: 建议添加文件末尾换行符
为符合 POSIX 标准并避免某些工具在处理时出现警告,建议在文件末尾补充一个换行符。🧰 Tools
🪛 Biome (1.9.4)
[error] 45-45: Unknown property is not allowed.
See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.(lint/correctness/noUnknownProperty)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
core/src/main/java/com/tlcsdm/core/javafx/richtext/JsonCodeArea.java(1 hunks)core/src/main/resources/com/tlcsdm/core/static/javafx/richtext/json-keywords.css(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- core/src/main/java/com/tlcsdm/core/javafx/richtext/JsonCodeArea.java
🧰 Additional context used
🪛 Biome (1.9.4)
core/src/main/resources/com/tlcsdm/core/static/javafx/richtext/json-keywords.css
[error] 29-29: Unknown property is not allowed.
See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.
(lint/correctness/noUnknownProperty)
[error] 30-30: Unknown property is not allowed.
See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.
(lint/correctness/noUnknownProperty)
[error] 34-34: Unknown property is not allowed.
See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.
(lint/correctness/noUnknownProperty)
[error] 35-38: Unknown property is not allowed.
See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.
(lint/correctness/noUnknownProperty)
[error] 39-39: Unknown property is not allowed.
See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.
(lint/correctness/noUnknownProperty)
⏰ Context from checks skipped due to timeout of 90000ms (9)
- GitHub Check: qodana
- GitHub Check: build (21, macos-latest, false)
- GitHub Check: build (17, windows-latest, false)
- GitHub Check: build (17, macos-latest, false)
- GitHub Check: build (17, ubuntu-latest, false)
- GitHub Check: build (21, windows-latest, false)
- GitHub Check: build (21, ubuntu-latest, false)
- GitHub Check: StepSecurity Harden-Runner
- GitHub Check: Summary
🔇 Additional comments (5)
core/src/main/resources/com/tlcsdm/core/static/javafx/richtext/json-keywords.css (5)
1-26: 许可声明完整且符合要求
许可证头部详细说明了使用条款和免责声明,符合开源规范,无需修改。
28-31: JSON 键的样式定义正确
.text-json-area .key使用了 JavaFX CSS 有效属性-fx-fill和-fx-font-weight,实现了预期的高亮和加粗效果。🧰 Tools
🪛 Biome (1.9.4)
[error] 29-29: Unknown property is not allowed.
See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.(lint/correctness/noUnknownProperty)
[error] 30-30: Unknown property is not allowed.
See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.(lint/correctness/noUnknownProperty)
33-36: JSON 值的样式定义正确
.text-json-area .value同样采用了 JavaFX CSS 属性,无语法或逻辑问题。🧰 Tools
🪛 Biome (1.9.4)
[error] 34-34: Unknown property is not allowed.
See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.(lint/correctness/noUnknownProperty)
38-40: 大括号和中括号样式定义正确
.brace和.bracket选择器配色清晰,符合 JSON 语法高亮需求。🧰 Tools
🪛 Biome (1.9.4)
[error] 39-39: Unknown property is not allowed.
See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.(lint/correctness/noUnknownProperty)
42-44: 逗号与冒号样式定义正确
使用黑色填充,视觉上与其他元素区分度高,满足可读性需求。
Signed-off-by: unknowIfGuestInDream <liang.tang.cx@gmail.com>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
♻️ Duplicate comments (6)
common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java (6)
275-292: POST请求参数未正确编码当构建POST请求体时,参数值未经过URL编码,这可能导致特殊字符处理错误。
316-318: 响应头处理错误代码错误地删除了响应头字符串的第一个字符,这会导致第一个响应头的第一个字符丢失。
225-326: sendAction方法过于复杂此方法职责过多,包括输入验证、请求构建、执行请求和处理响应,代码行数过多(超过90行),难以维护和测试。
344-350: 🛠️ Refactor suggestion缺少URL验证
在打开浏览器前,代码仅检查URL是否为空,但未验证格式是否正确。
建议添加URL验证:
@FXML private void toBrowerAction(ActionEvent event) { String url = urlTextField.getText(); - if (url.isEmpty()) { + if (url.isEmpty() || !isValidUrl(url)) { + notificationBuilder.text(I18nUtils.get("common.tool.debug.httpTool.error.invalidUrl")); + notificationBuilder.showWarning(); return; } CoreUtil.openWeb(url); } +/** + * 验证URL是否有效 + */ +private boolean isValidUrl(String url) { + try { + new java.net.URL(url).toURI(); + return true; + } catch (Exception e) { + return false; + } +}
304-308: 🛠️ Refactor suggestionHTTP状态码处理过于严格
代码仅将状态码200视为成功,忽略了其他有效的成功状态码(如201、202、204等)。
建议修改为:
- if (response == null || response.statusCode() != 200) { + if (response == null) { notificationBuilder.text(I18nUtils.get("common.tool.debug.httpTool.error.request")); notificationBuilder.showError(); return; + } + // 2xx状态码都表示成功 + if (response.statusCode() < 200 || response.statusCode() >= 300) { + notificationBuilder.text(I18nUtils.get("common.tool.debug.httpTool.error.request") + " - " + response.statusCode()); + notificationBuilder.showWarning(); + // 继续处理响应,以便用户可以查看错误详情 }
322-325: 🛠️ Refactor suggestion缺少响应类型检查
代码尝试将所有响应格式化为JSON,而没有检查Content-Type是否真的是JSON。
建议修改为:
HttpHeaders headers = response.headers(); + +// 获取Content-Type并根据类型处理响应 +String contentType = headers.firstValue("Content-Type").orElse(""); +boolean isJsonResponse = contentType.contains("application/json") || + contentType.contains("text/json") || + (response.body().startsWith("{") && response.body().endsWith("}")) || + (response.body().startsWith("[") && response.body().endsWith("]")); StringBuffer headerStringBuffer = new StringBuffer(); headers.map().forEach((name, values) -> { String value = String.join(", ", values); headerStringBuffer.append(name).append(":").append(value).append("\n"); }); ResponseHeaderTextArea.setText(headerStringBuffer.toString()); String res = response.body(); -if (DependencyUtil.hasJackson()) { +if (DependencyUtil.hasJackson() && isJsonResponse) { res = JacksonUtil.formatJson(res); } ResponseBodyTextArea.setText(res);
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java(1 hunks)common/src/main/resources/com/tlcsdm/jfxcommon/fxml/httpTool.fxml(1 hunks)common/src/main/resources/com/tlcsdm/jfxcommon/i18n/messages_en.properties(1 hunks)common/src/main/resources/com/tlcsdm/jfxcommon/i18n/messages_ja.properties(1 hunks)common/src/main/resources/com/tlcsdm/jfxcommon/i18n/messages_zh.properties(1 hunks)
✅ Files skipped from review due to trivial changes (3)
- common/src/main/resources/com/tlcsdm/jfxcommon/i18n/messages_zh.properties
- common/src/main/resources/com/tlcsdm/jfxcommon/i18n/messages_en.properties
- common/src/main/resources/com/tlcsdm/jfxcommon/i18n/messages_ja.properties
🚧 Files skipped from review as they are similar to previous changes (1)
- common/src/main/resources/com/tlcsdm/jfxcommon/fxml/httpTool.fxml
⏰ Context from checks skipped due to timeout of 90000ms (9)
- GitHub Check: qodana
- GitHub Check: build (21, windows-latest, false)
- GitHub Check: build (21, ubuntu-latest, false)
- GitHub Check: build (21, macos-latest, false)
- GitHub Check: build (17, windows-latest, false)
- GitHub Check: build (17, ubuntu-latest, false)
- GitHub Check: build (17, macos-latest, false)
- GitHub Check: StepSecurity Harden-Runner
- GitHub Check: Summary
Signed-off-by: unknowIfGuestInDream <liang.tang.cx@gmail.com>
Signed-off-by: unknowIfGuestInDream <liang.tang.cx@gmail.com>
|



Fixes #1007
Proposed Changes
Readiness Checklist
Author/Contributor
Reviewing Maintainer
enhancement,bug,documentationordependenciesSummary by Sourcery
Add HTTP debugging tool and enhance HTTP utility classes with comprehensive HTTP method support and JSON handling
New Features:
Enhancements:
Tests:
Summary by CodeRabbit