diff --git a/hutool-ai/src/main/java/cn/hutool/ai/core/BaseAIService.java b/hutool-ai/src/main/java/cn/hutool/ai/core/BaseAIService.java index 18d365a506188f5b0f086d150dd7f598343f3d85..08cfa49b375d0e0cec3d9c64fb2184f0fa48a490 100644 --- a/hutool-ai/src/main/java/cn/hutool/ai/core/BaseAIService.java +++ b/hutool-ai/src/main/java/cn/hutool/ai/core/BaseAIService.java @@ -151,15 +151,25 @@ public class BaseAIService { os.write(jsonInputString.getBytes()); os.flush(); } + // 检查响应状态 + if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { + callback.accept("{\"error\":\"HTTP-" + connection.getResponseCode() + "\"}"); + return; + } // 读取流式响应 try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { String line; while ((line = reader.readLine()) != null) { + if (line.startsWith("data:")) { + line = line.substring(5).trim(); + } + if ("[DONE]".equals(line)) break; // 调用回调函数处理每一行数据 callback.accept(line); } } + } catch (Exception e) { callback.accept("{\"error\": \"" + e.getMessage() + "\"}"); } finally {