如何通过ID获取单个用户?接口返回全量用户的问题解决
问题分析与修复方案
问题根源
你代码里的核心问题出在UserRest.getUserById方法调用外部接口的环节:
- 构造的URL是
http://localhost:8080/messenger/api/user/,这是获取所有用户列表的接口,没有拼接当前请求的id参数,所以返回的是用户数组。 - 你直接把这个数组响应写入了
output.txt,自然得不到单个用户的JSON对象。
修复方案
方案1:调用外部的单个用户接口(推荐)
如果外部服务提供了通过ID获取单个用户的接口(比如路径为/user/{id}),直接修改URL拼接id即可:
@GET @Path("/{id}") @Produces(MediaType.APPLICATION_JSON) public User getUserById(@PathParam("id") long id) throws IOException { // 拼接id到外部接口URL URL url = new URL("http://localhost:8080/messenger/api/user/" + id); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); int responseCode = connection.getResponseCode(); if(responseCode != 200) { System.out.println("Error: Response code " + responseCode); } Scanner scanner = new Scanner(url.openStream()); StringBuilder response = new StringBuilder(); while (scanner.hasNext()) { response.append(scanner.nextLine()); } scanner.close(); String responseData = response.toString(); // 注意:文件路径的反斜杠需要转义 FileWriter fileWriter = new FileWriter( "C:\\Users\\ETHAN\\Downloads\\My_Java_Solutions-main (7)\\My_Java_Solutions-main\\service_example\\output.txt"); PrintWriter printWriter = new PrintWriter(fileWriter); printWriter.print(responseData); printWriter.close(); logger.info("Data saved to file."); return userRepository.getById(id); }
方案2:解析用户数组筛选目标用户(无单个接口时用)
如果外部服务没有提供单个用户接口,只能先获取所有用户数组,再解析筛选出对应ID的用户:
首先引入JSON解析库(比如Jackson),然后修改代码:
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; @GET @Path("/{id}") @Produces(MediaType.APPLICATION_JSON) public User getUserById(@PathParam("id") long id) throws IOException { URL url = new URL("http://localhost:8080/messenger/api/user/"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); int responseCode = connection.getResponseCode(); if(responseCode != 200) { System.out.println("Error: Response code " + responseCode); } Scanner scanner = new Scanner(url.openStream()); StringBuilder response = new StringBuilder(); while (scanner.hasNext()) { response.append(scanner.nextLine()); } scanner.close(); String responseData = response.toString(); // 解析JSON数组为用户列表 ObjectMapper objectMapper = new ObjectMapper(); List<User> userList = objectMapper.readValue(responseData, new TypeReference<List<User>>() {}); // 筛选目标ID的用户 User targetUser = userList.stream() .filter(user -> user.getId() == id) .findFirst() .orElse(null); // 将目标用户转为JSON写入文件 String targetUserJson = objectMapper.writeValueAsString(targetUser); // 注意:文件路径的反斜杠需要转义 FileWriter fileWriter = new FileWriter( "C:\\Users\\ETHAN\\Downloads\\My_Java_Solutions-main (7)\\My_Java_Solutions-main\\service_example\\output.txt"); PrintWriter printWriter = new PrintWriter(fileWriter); printWriter.print(targetUserJson); printWriter.close(); logger.info("Data saved to file."); return userRepository.getById(id); }
额外注意事项
- 文件路径中的反斜杠必须转义:你当前代码里的路径
"C:\Users\ETHAN..."会因为未转义的反斜杠编译报错,需要改成"C:\\Users\\ETHAN..."或者用正斜杠"C:/Users/ETHAN..."。 - 补充异常处理:当前代码仅打印响应码错误,建议补充IO异常的捕获逻辑,避免程序意外崩溃。
内容的提问来源于stack exchange,提问作者HIZAM
相关产品推荐
相关产品推荐

