第109批:快问快答输出侧答案检测改方向感知(防林地府邸误伤)+联网兜底多后端轮询(好搜/Bing/搜狗替代单点DDG)+失败诊断日志
Auto Release / build (push) Successful in 2m50s
Auto Release / build (push) Successful in 2m50s
This commit is contained in:
@@ -44,6 +44,13 @@ public class AIChatManager {
|
||||
private final Map<String, String> quizAnswerMap = new ConcurrentHashMap<>();
|
||||
/** ★ 第108批续:玩家名 → 当前检测到的归一化题目(回复处理完即清,防跨请求误判) */
|
||||
private final Map<String, String> quizContext = new ConcurrentHashMap<>();
|
||||
/**
|
||||
* ★ 第109批:作弊意图上下文(玩家名 → 该玩家命中过的题目归一化集合,逗号分隔)。
|
||||
* 玩家发过题目原文/题号即视为「有作弊意图」,此后其所有回复的输出侧答案检测
|
||||
* 不但查该题答案,还查「答案⊆回复」方向(只查该玩家的题目,不扩散到全局,防误伤)。
|
||||
* 回复处理完后不清除(跨轮次有效,玩家可能分多次追问同一题),玩家退出时清理。
|
||||
*/
|
||||
private final Map<String, String> quizCheatIntent = new ConcurrentHashMap<>();
|
||||
private BukkitTask quizReloadTask = null;
|
||||
|
||||
// ★ 互动指标跳过日志静默:首次跳过记一条,之后只在状态变化(从≥→<)时再记
|
||||
@@ -856,6 +863,9 @@ public class AIChatManager {
|
||||
+ prompt.substring(0, Math.min(50, prompt.length())));
|
||||
if (player != null) {
|
||||
quizContext.put(player.getName(), quizHit);
|
||||
// ★ 第109批:记录作弊意图(追加,不覆盖——玩家可能连发多题)
|
||||
quizCheatIntent.merge(player.getName(), quizHit,
|
||||
(oldV, newV) -> oldV.contains(newV) ? oldV : oldV + "," + newV);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1107,7 +1117,7 @@ public class AIChatManager {
|
||||
}
|
||||
|
||||
// ★ 第69批-问题2:回复输出守卫(双保险),拦截代码块/破甲泄露
|
||||
reply = sanitizeReply(reply);
|
||||
reply = sanitizeReply(reply, player != null ? player.getName() : null);
|
||||
|
||||
// 发送回复
|
||||
if (broadcast) {
|
||||
@@ -1397,7 +1407,7 @@ public class AIChatManager {
|
||||
* 2. 含破甲泄露特征(模型名/供应商/提示词等) → 整条拒发
|
||||
* 3. 命中敏感话题关键词 → 改发角色化婉拒(保留正常闲聊)
|
||||
*/
|
||||
private String sanitizeReply(String reply) {
|
||||
private String sanitizeReply(String reply, String playerName) {
|
||||
if (reply == null || reply.isEmpty()) return reply;
|
||||
String r = reply.trim();
|
||||
// ★ 第84批:trim 后为空(纯空白/换行/空格)→ 返回婉拒,不广播空白
|
||||
@@ -1486,9 +1496,10 @@ public class AIChatManager {
|
||||
return fallbackDodge();
|
||||
}
|
||||
|
||||
// ★ 第108批续:输出侧答案检测(防 AI 直接给答案)——全面检查所有题目答案,
|
||||
// 不依赖题目上下文(玩家发题号/转述/追问时也能拦)。拆思路若未说出答案原文则放行。
|
||||
String quizAnswerHit = matchQuizAnswer(r);
|
||||
// ★ 第109批:输出侧答案检测(防 AI 直接给答案)——方向感知 + 作弊意图作用域。
|
||||
// 方向A(回复整段=答案)对所有玩家生效;方向B(回复含答案原文)只查
|
||||
// 该玩家命中过的题目,普通玩家闲聊提到答案词不误伤。
|
||||
String quizAnswerHit = matchQuizAnswer(r, playerName);
|
||||
if (quizAnswerHit != null) {
|
||||
plugin.getLogger().warning("[AI聊天] 输出守卫:回复疑似直接给出答案[" + quizAnswerHit + "],拦截。原文={" + r + "}");
|
||||
return fallbackDodge();
|
||||
@@ -1762,23 +1773,51 @@ public class AIChatManager {
|
||||
}
|
||||
|
||||
/**
|
||||
* ★ 第108批续:输出侧答案检测(防 AI 直接给答案)——全面检查,不依赖题目上下文。
|
||||
* 用户抓现行两类漏拦:①玩家发题号/答案(如"12"),AI 直接报答案;②玩家转述题目
|
||||
* (变体检测不到),AI 直接给答案。两者都没题目上下文,旧逻辑全漏。
|
||||
* 现改为:回复归一化后 contains 任一答案即拦。
|
||||
* 防误杀过滤:单字符答案(如选项 B/D)与纯数字答案(如 16/3/12000)跳过
|
||||
* ("16"在正常回复里太常见,误杀成本高于漏拦;中文/词组答案如"高压""1个下界之星"
|
||||
* "下界之星""密码"等仍检查)。
|
||||
* 返回命中的答案(归一化后),未命中返回 null。
|
||||
* ★ 第109批:玩家退出时清理其作弊意图记录(防内存随在线玩家数无限增长)。
|
||||
* 由 Main.onPlayerQuit 调用。
|
||||
*/
|
||||
private String matchQuizAnswer(String text) {
|
||||
public void clearQuizCheatIntent(String playerName) {
|
||||
if (playerName != null) {
|
||||
quizCheatIntent.remove(playerName);
|
||||
quizContext.remove(playerName);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ★ 第109批:输出侧答案检测(防 AI 直接给答案)——方向感知 + 作弊意图作用域。
|
||||
* <p>
|
||||
* 背景(第108批续的缺陷):旧版遍历「全部答案」做 norm.contains(a),
|
||||
* 任何含答案原文的正常回复都被误伤(玩家问"林地府邸一般生成在哪",
|
||||
* AI 答"林地府邸"——"林地府邸"恰是某题答案 → 误拦)。
|
||||
* <p>
|
||||
* 新逻辑(两个方向):
|
||||
* 方向A「回复⊆答案」:答案归一化后 contains 回复归一化 → 回复整段就是答案
|
||||
* (玩家发题号"12"、答案"高压苦力怕"等短回复场景)。
|
||||
* 方向B「答案⊆回复」:回复归一化 contains 答案 → 回复里夹着答案原文。
|
||||
* 仅对「有作弊意图的玩家」生效(其命中过的题目集合内)——
|
||||
* 普通玩家闲聊提到答案词(如讨论"林地府邸")不拦,只有把题目发给 AI
|
||||
* 的人(quizCheatIntent 有记录)才被严格检查,防误伤。
|
||||
* <p>
|
||||
* 防误杀过滤:单字符答案(B/D/1)与纯数字答案(16/12000)跳过——
|
||||
* 短答案在正常聊天里太常见,误杀成本高于漏拦。
|
||||
*
|
||||
* @param text 模型回复原文
|
||||
* @param playerName 发起请求的玩家(可 null,自动互动路径无玩家)
|
||||
* @return 命中的答案(归一化后),未命中返回 null
|
||||
*/
|
||||
private String matchQuizAnswer(String text, String playerName) {
|
||||
if (text == null || quizAnswerMap.isEmpty()) return null;
|
||||
String norm = normalizeQuizText(text);
|
||||
if (norm.isEmpty()) return null;
|
||||
for (String a : quizAnswerMap.values()) {
|
||||
String intent = (playerName == null) ? null : quizCheatIntent.get(playerName);
|
||||
for (Map.Entry<String, String> e : quizAnswerMap.entrySet()) {
|
||||
String a = e.getValue();
|
||||
if (a == null || a.length() < 2) continue; // 单字符答案跳过(B/D/1)
|
||||
if (a.matches("\\d+")) continue; // 纯数字答案跳过(防误杀"16个")
|
||||
if (norm.contains(a)) return a;
|
||||
// 方向A:回复整段就是答案(严格,对所有玩家生效——回复整段=答案必是作弊)
|
||||
if (a.contains(norm)) return a;
|
||||
// 方向B:回复里夹着答案原文(仅限有作弊意图的玩家,防误伤普通闲聊)
|
||||
if (intent != null && intent.contains(e.getKey()) && norm.contains(a)) return a;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -2366,7 +2405,7 @@ public class AIChatManager {
|
||||
|
||||
String reply = parseChatResponse(response.body());
|
||||
if (reply != null) {
|
||||
reply = sanitizeReply(reply);
|
||||
reply = sanitizeReply(reply, null);
|
||||
Bukkit.broadcastMessage("§d§l[AI] §f" + reply);
|
||||
recordIssue("[自动] " + prompt.substring(0, Math.min(100, prompt.length())), reply,
|
||||
"system", defaultModelFull, 200, null);
|
||||
|
||||
@@ -421,6 +421,11 @@ public class Main extends JavaPlugin
|
||||
}
|
||||
}
|
||||
|
||||
// ★ 第109批:清理该玩家的快问快答作弊意图记录(防内存随在线玩家数增长)
|
||||
if (aiChatManager != null) {
|
||||
aiChatManager.clearQuizCheatIntent(e.getPlayer().getName());
|
||||
}
|
||||
|
||||
// ★ 第58批-问题4:玩家下线时触发一次在线玩家同步
|
||||
// Bukkit.getOnlinePlayers() 已不含下线玩家 → 对账检出差异 → 推送更新名单
|
||||
// → PHP 端移除下线玩家。定时心跳保持不动。
|
||||
|
||||
@@ -17,13 +17,16 @@ import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* 联网搜索工具(第74批,2026-11-03)。
|
||||
* 联网搜索工具(第74批,2026-11-03;第109批重构兜底链路)。
|
||||
* <p>
|
||||
* 提供两种搜索后端:
|
||||
* <ul>
|
||||
* <li><b>DeepSeek Search API</b>(优先):POST https://api.deepseek.com/v1/tools/search
|
||||
* 与聊天 API 共用 Bearer key,返回结构化 JSON(title/url/snippet/summary/content)。</li>
|
||||
* <li><b>DuckDuckGo HTML</b>(兜底):无需 API key,解析 HTML 搜索结果页。</li>
|
||||
* <li><b>公开搜索 HTML 兜底</b>(第109批起多后端轮询):DeepSeek 失败/无 key 时,
|
||||
* 依次尝试 好搜(so.com) → Bing(cn.bing.com) → 搜狗(sogou.com),
|
||||
* 首个解析出结果的后端即返回。不再单点依赖 DuckDuckGo(实测多数环境超时/不可达)。
|
||||
* 百度实测反爬(200 但 0 结果)、minecraft.wiki API 403,均不纳入。</li>
|
||||
* </ul>
|
||||
* 同时提供 DeepSeek Fetch API(POST /v1/tools/fetch)抓取单页 URL 返回 Markdown。
|
||||
* <p>
|
||||
@@ -39,12 +42,15 @@ public class WebSearchTool {
|
||||
private static final String DEEPSEEK_SEARCH_URL = "https://api.deepseek.com/v1/tools/search";
|
||||
private static final String DEEPSEEK_FETCH_URL = "https://api.deepseek.com/v1/tools/fetch";
|
||||
|
||||
// ★ 第109批:公开搜索兜底后端(按实测质量排序:好搜摘要最全 → Bing → 搜狗)
|
||||
private static final String[] FALLBACK_BACKENDS = {"so", "bing", "sogou"};
|
||||
|
||||
/**
|
||||
* 联网搜索,返回摘要结果文本。
|
||||
* 优先用 DeepSeek Search API(如果有 key),否则回退到 DuckDuckGo HTML。
|
||||
* 优先用 DeepSeek Search API(如果有 key),失败时按序轮询公开搜索后端。
|
||||
*
|
||||
* @param query 搜索关键词
|
||||
* @param apiKey DeepSeek API key(可为 null/空,则回退 DDG)
|
||||
* @param apiKey DeepSeek API key(可为 null/空,则直接走公开搜索兜底)
|
||||
* @return 搜索结果摘要文本;全部失败返回 null
|
||||
*/
|
||||
public static String search(String query, String apiKey) {
|
||||
@@ -56,10 +62,28 @@ public class WebSearchTool {
|
||||
if (dsResult != null) return dsResult;
|
||||
}
|
||||
|
||||
// 兜底:DuckDuckGo HTML
|
||||
return duckDuckGoSearch(query);
|
||||
// 兜底:公开搜索后端轮询(首个有结果即返回)
|
||||
for (String backend : FALLBACK_BACKENDS) {
|
||||
String result = publicSearch(backend, query);
|
||||
if (result != null) return result;
|
||||
}
|
||||
System.out.println("[WebSearchTool] 搜索无结果: DeepSeek 与全部公开后端("
|
||||
+ String.join("/", FALLBACK_BACKENDS) + ") 均失败, query=" + query);
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 公开搜索后端路由 */
|
||||
private static String publicSearch(String backend, String query) {
|
||||
switch (backend) {
|
||||
case "so": return soSearch(query);
|
||||
case "bing": return bingSearch(query);
|
||||
case "sogou": return sogouSearch(query);
|
||||
default: return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== DeepSeek Search API ====================
|
||||
|
||||
/**
|
||||
* 使用 DeepSeek Search API 搜索。
|
||||
* POST https://api.deepseek.com/v1/tools/search
|
||||
@@ -88,7 +112,10 @@ public class WebSearchTool {
|
||||
if (code != 200) {
|
||||
// 读取错误体用于诊断
|
||||
String err = readErrorBody(conn);
|
||||
return null; // 回退到 DDG
|
||||
// ★ 第109批:DeepSeek 失败诊断(此前静默回退,key 无效/403 全黑盒)
|
||||
System.out.println("[WebSearchTool] DeepSeek Search HTTP " + code
|
||||
+ " errBody=" + (err == null ? "" : err.substring(0, Math.min(200, err.length()))));
|
||||
return null; // 回退到公开搜索
|
||||
}
|
||||
|
||||
BufferedReader reader = new BufferedReader(
|
||||
@@ -105,7 +132,11 @@ public class WebSearchTool {
|
||||
if (!json.has("results")) return null;
|
||||
|
||||
JsonArray results = json.getAsJsonArray("results");
|
||||
if (results.size() == 0) return null;
|
||||
if (results.size() == 0) {
|
||||
// ★ 第109批:DeepSeek 200 但 0 结果(查询无命中,与失败区分)
|
||||
System.out.println("[WebSearchTool] DeepSeek Search 200 但 results 为空, query=" + query);
|
||||
return null;
|
||||
}
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("搜索结果(共").append(results.size()).append("条):\n");
|
||||
@@ -124,10 +155,14 @@ public class WebSearchTool {
|
||||
}
|
||||
return sb.toString();
|
||||
} catch (Exception e) {
|
||||
// ★ 第109批:DeepSeek 异常诊断
|
||||
System.out.println("[WebSearchTool] DeepSeek Search 异常: " + e.getClass().getSimpleName() + ": " + e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== DeepSeek Fetch API ====================
|
||||
|
||||
/**
|
||||
* 使用 DeepSeek Fetch API 抓取单个 URL,返回 Markdown 内容。
|
||||
* POST https://api.deepseek.com/v1/tools/fetch
|
||||
@@ -153,7 +188,12 @@ public class WebSearchTool {
|
||||
w.close();
|
||||
|
||||
int code = conn.getResponseCode();
|
||||
if (code != 200) return null;
|
||||
if (code != 200) {
|
||||
String err = readErrorBody(conn);
|
||||
System.out.println("[WebSearchTool] DeepSeek Fetch HTTP " + code
|
||||
+ " errBody=" + (err == null ? "" : err.substring(0, Math.min(200, err.length()))));
|
||||
return null;
|
||||
}
|
||||
|
||||
BufferedReader reader = new BufferedReader(
|
||||
new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
|
||||
@@ -171,74 +211,173 @@ public class WebSearchTool {
|
||||
if (content.isEmpty()) return null;
|
||||
return title.isEmpty() ? content : title + "\n\n" + content;
|
||||
} catch (Exception e) {
|
||||
System.out.println("[WebSearchTool] DeepSeek Fetch 异常: " + e.getClass().getSimpleName() + ": " + e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** DuckDuckGo HTML 搜索兜底 */
|
||||
private static String duckDuckGoSearch(String query) {
|
||||
// ==================== 公开搜索后端(第109批) ====================
|
||||
|
||||
/**
|
||||
* 好搜(so.com) 搜索。实测摘要最全(含百科/金字塔等级等正文片段),质量最高,排第一。
|
||||
* 页面结构:<h3 class="res-title"><a href="...">标题</a></h3> + <p class="res-desc">摘要</p>
|
||||
*/
|
||||
private static String soSearch(String query) {
|
||||
try {
|
||||
String encoded = URLEncoder.encode(query, StandardCharsets.UTF_8.name());
|
||||
String url = "https://html.duckduckgo.com/html/?q=" + encoded;
|
||||
String url = "https://www.so.com/s?q=" + URLEncoder.encode(query, StandardCharsets.UTF_8.name());
|
||||
String html = httpGet(url);
|
||||
if (html == null) return null;
|
||||
|
||||
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
|
||||
conn.setRequestMethod("GET");
|
||||
conn.setRequestProperty("User-Agent", USER_AGENT);
|
||||
conn.setRequestProperty("Accept", "text/html");
|
||||
conn.setConnectTimeout(TIMEOUT_MS);
|
||||
conn.setReadTimeout(TIMEOUT_MS);
|
||||
|
||||
int code = conn.getResponseCode();
|
||||
if (code != 200) return null;
|
||||
|
||||
BufferedReader reader = new BufferedReader(
|
||||
new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
|
||||
StringBuilder html = new StringBuilder();
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
html.append(line).append("\n");
|
||||
// 标题+链接
|
||||
Pattern tp = Pattern.compile(
|
||||
"<h3[^>]*class=\"[^\"]*res-title[^\"]*\"[^>]*>\\s*<a[^>]*href=\"([^\"]+)\"[^>]*>(.*?)</a>",
|
||||
Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
|
||||
Matcher tm = tp.matcher(html);
|
||||
List<String> titles = new ArrayList<>();
|
||||
List<String> urls = new ArrayList<>();
|
||||
while (tm.find() && titles.size() < MAX_RESULTS) {
|
||||
String t = stripTags(tm.group(2));
|
||||
if (!t.isEmpty()) {
|
||||
titles.add(t);
|
||||
urls.add(tm.group(1));
|
||||
}
|
||||
}
|
||||
// 摘要(res-desc,与标题按序对应;数量可能略少,缺失留空)
|
||||
Pattern sp = Pattern.compile(
|
||||
"<p[^>]*class=\"[^\"]*res-desc[^\"]*\"[^>]*>(.*?)</p>",
|
||||
Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
|
||||
Matcher sm = sp.matcher(html);
|
||||
List<String> snippets = new ArrayList<>();
|
||||
while (sm.find() && snippets.size() < MAX_RESULTS) {
|
||||
snippets.add(stripTags(sm.group(1)));
|
||||
}
|
||||
reader.close();
|
||||
conn.disconnect();
|
||||
|
||||
return parseDdgResults(html.toString());
|
||||
return buildResult("好搜", titles, snippets, urls);
|
||||
} catch (Exception e) {
|
||||
System.out.println("[WebSearchTool] 好搜异常: " + e.getClass().getSimpleName() + ": " + e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 解析 DuckDuckGo HTML 搜索结果页 */
|
||||
private static String parseDdgResults(String html) {
|
||||
List<String> titles = new ArrayList<>();
|
||||
List<String> snippets = new ArrayList<>();
|
||||
/**
|
||||
* Bing(cn.bing.com) 搜索。标题稳定,摘要常缺(无 <p> 时留空)。
|
||||
* 页面结构:<li class="b_algo"><h2><a href="...">标题</a></h2>...<p>摘要</p>
|
||||
*/
|
||||
private static String bingSearch(String query) {
|
||||
try {
|
||||
String url = "https://cn.bing.com/search?q=" + URLEncoder.encode(query, StandardCharsets.UTF_8.name());
|
||||
String html = httpGet(url);
|
||||
if (html == null) return null;
|
||||
|
||||
Pattern titlePattern = Pattern.compile(
|
||||
"<a[^>]*class=\"result__a\"[^>]*>(.*?)</a>", Pattern.DOTALL);
|
||||
Pattern snippetPattern = Pattern.compile(
|
||||
"<a[^>]*class=\"result__snippet\"[^>]*>(.*?)</a>", Pattern.DOTALL);
|
||||
Pattern tp = Pattern.compile(
|
||||
"<li class=\"b_algo\".*?<h2><a[^>]*href=\"([^\"]+)\"[^>]*>(.*?)</a>",
|
||||
Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
|
||||
Matcher tm = tp.matcher(html);
|
||||
List<String> titles = new ArrayList<>();
|
||||
List<String> urls = new ArrayList<>();
|
||||
List<String> snippets = new ArrayList<>();
|
||||
while (tm.find() && titles.size() < MAX_RESULTS) {
|
||||
String t = stripTags(tm.group(2));
|
||||
if (!t.isEmpty()) {
|
||||
titles.add(t);
|
||||
urls.add(tm.group(1));
|
||||
// 摘要:该 li 内首个 <p>(可能没有)
|
||||
int liEnd = html.indexOf("</li>", tm.end());
|
||||
String li = liEnd > 0 ? html.substring(tm.start(), liEnd) : "";
|
||||
Matcher sm = Pattern.compile("<p[^>]*>(.*?)</p>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL).matcher(li);
|
||||
snippets.add(sm.find() ? stripTags(sm.group(1)) : "");
|
||||
}
|
||||
}
|
||||
|
||||
Matcher tm = titlePattern.matcher(html);
|
||||
Matcher sm = snippetPattern.matcher(html);
|
||||
|
||||
while (tm.find() && titles.size() < MAX_RESULTS) {
|
||||
titles.add(stripTags(tm.group(1)));
|
||||
return buildResult("Bing", titles, snippets, urls);
|
||||
} catch (Exception e) {
|
||||
System.out.println("[WebSearchTool] Bing异常: " + e.getClass().getSimpleName() + ": " + e.getMessage());
|
||||
return null;
|
||||
}
|
||||
while (sm.find() && snippets.size() < MAX_RESULTS) {
|
||||
snippets.add(stripTags(sm.group(1)));
|
||||
}
|
||||
|
||||
/**
|
||||
* 搜狗(sogou.com) 搜索。仅标题稳定(摘要结构多变),作为最后兜底。
|
||||
* 页面结构:<h3><a href="...">标题</a></h3>
|
||||
*/
|
||||
private static String sogouSearch(String query) {
|
||||
try {
|
||||
String url = "https://www.sogou.com/web?query=" + URLEncoder.encode(query, StandardCharsets.UTF_8.name());
|
||||
String html = httpGet(url);
|
||||
if (html == null) return null;
|
||||
|
||||
Pattern tp = Pattern.compile(
|
||||
"<h3[^>]*>\\s*<a[^>]*href=\"([^\"]+)\"[^>]*>(.*?)</a>",
|
||||
Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
|
||||
Matcher tm = tp.matcher(html);
|
||||
List<String> titles = new ArrayList<>();
|
||||
List<String> urls = new ArrayList<>();
|
||||
List<String> snippets = new ArrayList<>();
|
||||
while (tm.find() && titles.size() < MAX_RESULTS) {
|
||||
String t = stripTags(tm.group(2));
|
||||
if (!t.isEmpty()) {
|
||||
titles.add(t);
|
||||
urls.add(tm.group(1));
|
||||
snippets.add("");
|
||||
}
|
||||
}
|
||||
|
||||
return buildResult("搜狗", titles, snippets, urls);
|
||||
} catch (Exception e) {
|
||||
System.out.println("[WebSearchTool] 搜狗异常: " + e.getClass().getSimpleName() + ": " + e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
int n = Math.min(titles.size(), snippets.size());
|
||||
if (n == 0) return null;
|
||||
|
||||
/** 统一拼装结果文本;无结果返回 null */
|
||||
private static String buildResult(String backend, List<String> titles, List<String> snippets, List<String> urls) {
|
||||
if (titles.isEmpty()) {
|
||||
System.out.println("[WebSearchTool] " + backend + " 解析 0 条结果");
|
||||
return null;
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("搜索结果(共").append(n).append("条):\n");
|
||||
for (int i = 0; i < n; i++) {
|
||||
sb.append("搜索结果(共").append(titles.size()).append("条,来源:").append(backend).append("):\n");
|
||||
for (int i = 0; i < titles.size(); i++) {
|
||||
sb.append(i + 1).append(". ").append(titles.get(i)).append("\n");
|
||||
sb.append(" ").append(snippets.get(i)).append("\n");
|
||||
if (i < snippets.size() && !snippets.get(i).isEmpty()) {
|
||||
sb.append(" 摘要: ").append(snippets.get(i)).append("\n");
|
||||
}
|
||||
if (i < urls.size() && !urls.get(i).isEmpty()) {
|
||||
sb.append(" 链接: ").append(urls.get(i)).append("\n");
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/** GET 请求拉整页;非 200 或异常返回 null(调用方决定下一个后端) */
|
||||
private static String httpGet(String urlStr) throws Exception {
|
||||
HttpURLConnection conn = (HttpURLConnection) new URL(urlStr).openConnection();
|
||||
conn.setRequestMethod("GET");
|
||||
conn.setRequestProperty("User-Agent", USER_AGENT);
|
||||
conn.setRequestProperty("Accept", "text/html");
|
||||
conn.setConnectTimeout(TIMEOUT_MS);
|
||||
conn.setReadTimeout(TIMEOUT_MS);
|
||||
|
||||
int code = conn.getResponseCode();
|
||||
if (code != 200) {
|
||||
String err = readErrorBody(conn);
|
||||
System.out.println("[WebSearchTool] HTTP " + code + " url=" + urlStr
|
||||
+ " errBody=" + (err == null ? "" : err.substring(0, Math.min(200, err.length()))));
|
||||
return null;
|
||||
}
|
||||
|
||||
BufferedReader reader = new BufferedReader(
|
||||
new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
|
||||
StringBuilder html = new StringBuilder();
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
html.append(line).append("\n");
|
||||
}
|
||||
reader.close();
|
||||
conn.disconnect();
|
||||
return html.toString();
|
||||
}
|
||||
|
||||
/** 读取 HTTP 错误响应体(用于诊断) */
|
||||
private static String readErrorBody(HttpURLConnection conn) {
|
||||
try {
|
||||
|
||||
Reference in New Issue
Block a user