Coze API流式接口
阅读时间:
1
min 文章字数:
203
字 发布日期:
2025-12-16
最近更新:
2025-09-23
阅读量:
-
java
/**
* 以流式方式请求 Coze 接口,逐行解析 JSON,拼接每个 content 字段。
* 兼容两种行格式:
* 1) 原始 JSON 行: {"content":"..."}
* 2) SSE 行: data: {"content":"..."}
*/
private String streamCozeContents(String cozeApi, String token, JSONObject entries){
StringBuilder contentBuilder = new StringBuilder(128);
HttpResponse response = null;
try {
response = HttpRequest.post(cozeApi)
.header("Authorization", "Bearer " + token)
.header("Content-Type", "application/json")
.timeout(0) // 流式必须禁用超时
.body(JSONUtil.toJsonStr(entries))
.execute();
try (BufferedReader br = new BufferedReader(new InputStreamReader(response.bodyStream(), StandardCharsets.UTF_8))) {
String line;
while ((line = br.readLine()) != null) {
String raw = line.trim();
if (raw.isEmpty()) { continue; }
if ("[DONE]".equals(raw) || "data: [DONE]".equals(raw)) { break; }
if (raw.startsWith("data:")) { raw = raw.substring(5).trim(); }
try {
if (JSONUtil.isTypeJSON(raw)) {
JSONObject obj = JSONUtil.parseObj(raw);
log.info("Coze response: {}", obj);
String c = obj.getStr("content");
if (c != null && obj.getStr("type").equals("answer") && obj.getStr("created_at") == null) { contentBuilder.append(c); }
}
} catch (Exception ignore) {
// 非 JSON 行,忽略
}
}
}
} catch (Exception e) {
log.error("stream coze error", e);
} finally {
if (response != null) {
try { response.close(); } catch (Exception ignore) {}
}
}
return contentBuilder.toString();
}