我怎样才能通过 id 只获得一个用户?

问题描述 投票:0回答:1
class UserRepository {
 public User getById(long id) {
        logger.info("Get User by id: " + id);
        return entityManager.find(User.class, id);
    }
}
class UserRest {
@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();
            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);
    }
}

我在txt文件中得到的结果 [{"id":15,"nick_name":"freddy","userType":"user"},{"id":17,"nick_name":"samy","userType":"user"},{ "id":29,"nick_name":"klien","userType":"user"},{"id":20,"nick_name":"sam","userType":"user"}] 我想在txt文件中的结果是 {"id":15,"nick_name":"freddy","userType":"user"}

java rest annotations postman httpresponse
1个回答
0
投票

你能展示你的“http://localhost:8080/messenger/api/user/”端点的代码吗?似乎您将 ID 传递给了端点,但它的查询返回的用户比您预期的要多。

因此,您可以编辑从该端点返回的响应,或者在返回响应时根据用户 ID 过滤响应。在将那行附加到最终结果之前,检查扫描仪的 while 循环中每一行的用户 ID。

© www.soinside.com 2019 - 2024. All rights reserved.