@@ -60,6 +60,9 @@ public class AnthropicClient {
6060 /** 模型 ID,如 "claude-sonnet-4-20250514",决定了使用哪个版本的 Claude */
6161 private final String model ;
6262
63+ /** 是否打印请求/响应报文,用于调试,默认 false */
64+ private final boolean debugPrintPayload ;
65+
6366 /**
6467 * Gson 实例,开启 PrettyPrinting 是为了调试时日志可读性更好。
6568 * 设为 static final 是因为 Gson 是线程安全的,全局共享一个实例即可。
@@ -136,13 +139,16 @@ public AnthropicClient() {
136139 this .apiKey = getConfig ("ANTHROPIC_API_KEY" ,
137140 getConfig ("ANTHROPIC_AUTH_TOKEN" , "" ));
138141 this .model = getConfig ("MODEL_ID" , "" );
142+ // 读取调试开关,默认不打印报文
143+ this .debugPrintPayload = Boolean .parseBoolean (getConfig ("DEBUG_PRINT_PAYLOAD" , "false" ));
139144
140145 // 启动时打印配置来源,方便调试 —— 生产环境中应该用日志框架替代 System.out
141146 // 注意:API Key 只打印前 8 位,这是安全最佳实践,防止密钥泄露到日志中
142147 System .out .println ("[AnthropicClient] base_url = " + baseUrl );
143148 System .out .println ("[AnthropicClient] model = " + model );
144149 System .out .println ("[AnthropicClient] api_key = " +
145150 (apiKey .isEmpty () ? "(NOT SET!)" : apiKey .substring (0 , Math .min (8 , apiKey .length ())) + "..." ));
151+ System .out .println ("[AnthropicClient] debug = " + debugPrintPayload );
146152 }
147153
148154 public String getModel () {
@@ -236,7 +242,9 @@ private String doPost(String path, String jsonBody) {
236242 }
237243
238244 // ===== 发送请求体 =====
239- System .out .println ("=====请求报文=====\n " +jsonBody .toString ());
245+ if (debugPrintPayload ) {
246+ System .out .println ("=====请求报文=====\n " + jsonBody );
247+ }
240248 byte [] bodyBytes = jsonBody .getBytes (StandardCharsets .UTF_8 );
241249 conn .setRequestProperty ("Content-Length" , String .valueOf (bodyBytes .length ));
242250 try (OutputStream os = conn .getOutputStream ()) {
@@ -263,14 +271,16 @@ private String doPost(String path, String jsonBody) {
263271 if (status < 200 || status >= 300 ) {
264272 throw new RuntimeException ("API Error (HTTP " + status + "): " + sb .toString ());
265273 }
266- // 格式化 JSON 响应报文
274+ // 格式化 JSON 响应报文(仅在调试模式下打印)
267275 String responseStr = sb .toString ();
268- try {
269- JsonObject responseJson = JsonParser .parseString (responseStr ).getAsJsonObject ();
270- System .out .println ("=====响应报文=====\n " + GSON .toJson (responseJson ));
271- } catch (Exception e ) {
272- // JSON 解析失败时直接输出原始字符串
273- System .out .println ("=====响应报文=====\n " + responseStr );
276+ if (debugPrintPayload ) {
277+ try {
278+ JsonObject responseJson = JsonParser .parseString (responseStr ).getAsJsonObject ();
279+ System .out .println ("=====响应报文=====\n " + GSON .toJson (responseJson ));
280+ } catch (Exception e ) {
281+ // JSON 解析失败时直接输出原始字符串
282+ System .out .println ("=====响应报文=====\n " + responseStr );
283+ }
274284 }
275285 return responseStr ;
276286
0 commit comments