2222import java .util .concurrent .ConcurrentHashMap ;
2323import java .util .regex .Pattern ;
2424
25-
2625public class CertificateManager {
2726 // 证书缓存
2827 private static final ConcurrentHashMap <String , ServerCertificateInfo > certificateCache = new ConcurrentHashMap <>();
@@ -52,8 +51,6 @@ public String getRingId() {
5251 public String getKeyId () {
5352 return keyId ;
5453 }
55-
56-
5754 }
5855
5956 private static List <String > getDnsNamesFromExtension (Extension sanExtension ) {
@@ -79,7 +76,6 @@ private static List<String> getDnsNamesFromExtension(Extension sanExtension) {
7976 * 检查内存缓存中是否存在证书
8077 */
8178 public static boolean hasCertificateInCache (String ep ) {
82- // 假设有一个静态的ConcurrentHashMap来存储证书缓存
8379 return certificateCache .containsKey (ep );
8480 }
8581
@@ -93,7 +89,6 @@ public static ServerCertificateInfo getServerCertificateFromCache(String ep) {
9389 public static ServerCertificateInfo getServerCertificate (String apiKey , String baseUrl , String ep ) throws IOException {
9490 // 首先检查内存缓存,用ep作为key
9591 if (hasCertificateInCache (ep )) {
96-
9792 return getServerCertificateFromCache (ep );
9893 }
9994
@@ -207,92 +202,139 @@ public static String loadCertificateLocally(String ep) throws IOException {
207202 return null ;
208203 }
209204
210-
211205 /**
212- * 使用API Key方式获取证书
206+ * 使用API Key方式获取证书 - 重构后降低复杂度
213207 */
214208 public static String loadCertificateByApiKey (String baseUrl , String apiKey , String ep , boolean aiccEnabled ) throws IOException {
215209 HttpURLConnection connection = null ;
216210 try {
217- // 修复URI构建问题
218- String certificateUrl ;
219- if (baseUrl .endsWith ("/" )) {
220- certificateUrl = baseUrl + "e2e/get/certificate" ;
221- } else {
222- certificateUrl = baseUrl + "/e2e/get/certificate" ;
211+ connection = createHttpConnection (baseUrl , apiKey );
212+ sendCertificateRequest (connection , ep , aiccEnabled );
213+ return processCertificateResponse (connection );
214+ } catch (IOException e ) {
215+ throw e ;
216+ } catch (Exception e ) {
217+ String errMsg = "通过API Key获取证书失败: " + e .getMessage ();
218+ throw new IOException (errMsg , e );
219+ } finally {
220+ if (connection != null ) {
221+ connection .disconnect ();
223222 }
223+ }
224+ }
224225
226+ /**
227+ * 创建HTTP连接
228+ */
229+ private static HttpURLConnection createHttpConnection (String baseUrl , String apiKey ) throws IOException {
230+ String certificateUrl = buildCertificateUrl (baseUrl );
231+ URL url = URI .create (certificateUrl ).toURL ();
232+ HttpURLConnection connection = (HttpURLConnection ) url .openConnection ();
225233
226- URL url = URI .create (certificateUrl ).toURL ();
227- connection = (HttpURLConnection ) url .openConnection ();
234+ connection .setRequestMethod ("POST" );
235+ connection .setRequestProperty ("Content-Type" , "application/json" );
236+ connection .setRequestProperty ("Authorization" , "Bearer " + apiKey );
237+ connection .setRequestProperty ("X-Session-Token" , "/e2e/get/certificate" );
228238
229- // 设置请求头
230- connection .setRequestMethod ("POST" );
231- connection .setRequestProperty ("Content-Type" , "application/json" );
232- connection .setRequestProperty ("Authorization" , "Bearer " + apiKey );
233- connection .setRequestProperty ("X-Session-Token" , "/e2e/get/certificate" );
239+ return connection ;
240+ }
234241
235- // 构建请求体
236- Map <String , Object > requestBody = new HashMap <>();
237- requestBody .put ("model" , ep );
238- if (aiccEnabled ) {
239- requestBody .put ("type" , "AICCv0.1" );
240- }
241- ObjectMapper mapper = new ObjectMapper ();
242- String jsonBody = mapper .writeValueAsString (requestBody );
242+ /**
243+ * 构建证书请求URL
244+ */
245+ private static String buildCertificateUrl (String baseUrl ) {
246+ if (baseUrl .endsWith ("/" )) {
247+ return baseUrl + "e2e/get/certificate" ;
248+ } else {
249+ return baseUrl + "/e2e/get/certificate" ;
250+ }
251+ }
252+
253+ /**
254+ * 发送证书请求
255+ */
256+ private static void sendCertificateRequest (HttpURLConnection connection , String ep , boolean aiccEnabled ) throws IOException {
257+ String jsonBody = buildRequestBody (ep , aiccEnabled );
243258
259+ connection .setDoOutput (true );
260+ try (OutputStream os = connection .getOutputStream ()) {
261+ byte [] input = jsonBody .getBytes (StandardCharsets .UTF_8 );
262+ os .write (input , 0 , input .length );
263+ }
264+ }
244265
245- // 发送请求
246- connection .setDoOutput (true );
247- try (OutputStream os = connection .getOutputStream ()) {
248- byte [] input = jsonBody .getBytes (StandardCharsets .UTF_8 );
249- os .write (input , 0 , input .length );
250- }
266+ /**
267+ * 构建请求体
268+ */
269+ private static String buildRequestBody (String ep , boolean aiccEnabled ) throws IOException {
270+ Map <String , Object > requestBody = new HashMap <>();
271+ requestBody .put ("model" , ep );
272+ if (aiccEnabled ) {
273+ requestBody .put ("type" , "AICCv0.1" );
274+ }
275+ ObjectMapper mapper = new ObjectMapper ();
276+ return mapper .writeValueAsString (requestBody );
277+ }
251278
252- // 处理响应
253- int responseCode = connection .getResponseCode ();
279+ /**
280+ * 处理证书响应
281+ */
282+ private static String processCertificateResponse (HttpURLConnection connection ) throws IOException {
283+ int responseCode = connection .getResponseCode ();
254284
285+ if (!isSuccessfulResponse (responseCode )) {
286+ handleErrorResponse (connection , responseCode );
287+ }
255288
256- if ( responseCode >= 200 && responseCode < 300 ) {
257- String responseBody = readResponseBody ( connection );
289+ return extractCertificateFromResponse ( connection );
290+ }
258291
292+ /**
293+ * 检查响应是否成功
294+ */
295+ private static boolean isSuccessfulResponse (int responseCode ) {
296+ return responseCode >= 200 && responseCode < 300 ;
297+ }
259298
260- Map <String , Object > responseJson = mapper .readValue (
261- responseBody ,
262- new TypeReference <HashMap <String , Object >>() {
263- }
264- );
299+ /**
300+ * 处理错误响应
301+ */
302+ private static void handleErrorResponse (HttpURLConnection connection , int responseCode ) throws IOException {
303+ String errorResponse = readErrorResponse (connection );
304+ String errorMsg = "证书请求失败,状态码: " + responseCode + ", 响应: " + errorResponse ;
305+ throw new IOException (errorMsg );
306+ }
265307
266- // 检查错误
267- if ( responseJson . containsKey ( "error" )) {
268- Object error = responseJson . get ( "error" );
269- String errorMsg = "获取证书失败: " + error ;
270- throw new IOException ( errorMsg );
271- }
308+ /**
309+ * 从响应中提取证书
310+ */
311+ private static String extractCertificateFromResponse ( HttpURLConnection connection ) throws IOException {
312+ String responseBody = readResponseBody ( connection );
313+ ObjectMapper mapper = new ObjectMapper ();
272314
273- if (responseJson .containsKey ("Certificate" )) {
274- return (String ) responseJson .get ("Certificate" );
275- } else {
276- String errorMsg = "响应中未找到Certificate字段" ;
277- throw new IOException (errorMsg );
315+ Map <String , Object > responseJson = mapper .readValue (
316+ responseBody ,
317+ new TypeReference <HashMap <String , Object >>() {
278318 }
279- } else {
280- String errorResponse = readErrorResponse (connection );
281- String errorMsg = "证书请求失败,状态码: " + responseCode + ", 响应: " + errorResponse ;
282- throw new IOException (errorMsg );
283- }
319+ );
284320
285- } catch (Exception e ) {
286- if (e instanceof IOException ) {
287- throw (IOException ) e ;
288- } else {
289- String errMsg = "通过API Key获取证书失败: " + e .getMessage ();
290- throw new IOException (errMsg , e );
291- }
292- } finally {
293- if (connection != null ) {
294- connection .disconnect ();
295- }
321+ validateResponse (responseJson );
322+
323+ if (responseJson .containsKey ("Certificate" )) {
324+ return (String ) responseJson .get ("Certificate" );
325+ } else {
326+ throw new IOException ("响应中未找到Certificate字段" );
327+ }
328+ }
329+
330+ /**
331+ * 验证响应数据
332+ */
333+ private static void validateResponse (Map <String , Object > responseJson ) throws IOException {
334+ if (responseJson .containsKey ("error" )) {
335+ Object error = responseJson .get ("error" );
336+ String errorMsg = "获取证书失败: " + error ;
337+ throw new IOException (errorMsg );
296338 }
297339 }
298340
@@ -342,7 +384,6 @@ public static void cacheServerCertificate(String cacheKey, PublicKey publicKey,
342384
343385 /**
344386 * 从PEM格式的X.509证书中提取公钥
345- *
346387 */
347388 public static PublicKey extractPublicKeyFromCertificate (String certificate ) throws GeneralSecurityException {
348389 try {
@@ -422,5 +463,4 @@ public static String readErrorResponse(HttpURLConnection connection) throws IOEx
422463 return errorResponse .toString ();
423464 }
424465 }
425-
426466}
0 commit comments