Java调用Skycrypt API获取Hypixel玩家当前Profile的问题
解决方案
核心思路
Skycrypt API返回的profiles对象是以随机字符串为键的JSON结构,无需硬编码这些键,只需遍历所有键值对,检查每个profile的current字段,即可找到标记为当前活跃的profile。
基于现有代码的修改实现
URL pseudo = new URL("https://sky.shiiyu.moe/api/v2/profile/CoopCarried"); BufferedReader in2 = new BufferedReader(new InputStreamReader(pseudo.openStream())); StringBuilder response2 = new StringBuilder(); String inputLine2; while ((inputLine2 = in2.readLine()) != null) { response2.append(inputLine2); } in2.close(); JSONObject json = new JSONObject(response2.toString()); JSONObject profiles = json.getJSONObject("profiles"); // 遍历所有profile的随机键 for (String profileKey : profiles.keySet()) { JSONObject profile = profiles.getJSONObject(profileKey); boolean isCurrent = profile.getBoolean("current"); if (isCurrent) { System.out.println("当前活跃Profile的键:" + profileKey); // 可在此处获取该profile的其他数据,例如: // String profileNickname = profile.getString("cute_name"); // System.out.println("Profile昵称:" + profileNickname); break; // 通常仅存在一个当前活跃Profile,找到后直接终止循环 } }
批量场景优化建议
- 异常处理:添加
IOException与JSON解析异常捕获,避免请求失败或格式错误导致程序崩溃。 - 改用现代HTTP客户端:原生
URL类功能有限,推荐使用Java 11+自带的HttpClient,支持异步请求,更适合批量处理百名玩家的场景:
HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://sky.shiiyu.moe/api/v2/profile/CoopCarried")) .build(); client.sendAsync(request, HttpResponse.BodyHandlers.ofString()) .thenApply(HttpResponse::body) .thenAccept(body -> { JSONObject json = new JSONObject(body); JSONObject profiles = json.getJSONObject("profiles"); for (String key : profiles.keySet()) { JSONObject profile = profiles.getJSONObject(key); if (profile.getBoolean("current")) { System.out.println("当前Profile键:" + key); } } }) .join();
- 并发控制:处理百名玩家请求时,使用线程池限制并发数,避免触发API限流机制。
内容的提问来源于stack exchange,提问作者CoopCarried
相关产品推荐
相关产品推荐

