首页 > 解决方案 > 通过 cURL (json) 显示消息(Spring Boot)

问题描述

我想显示以特定 id 开头的消息,例如,我选择了 id = 4。它可以工作

curl -H "Content-Type: application/json" localhost:8080/api/unread/4

但是告诉我 curl 请求写错了,他应该发送 Json 并返回 Json,对不起,我可能写错了一个例子,但它应该看起来像这样 -

curl -H "Content-Type: application/json" -d "{id=4"}" localhost:8080/api/unread

休息服务

@Service
public class RestService {
    private final RestTemplate restTemplate;

    public RestService(RestTemplateBuilder restTemplateBuilder) {
        this.restTemplate = restTemplateBuilder.build();
    }

    public Message saveMessage(Message message) {
        String url = "http://localhost:8080/api/save";

        return this.restTemplate.postForObject(url, message, Message.class);
    }

    public void updateMessage(long id, Message message) {
        String url = String.format("http://localhost:8080/api/update/%d", id);

        this.restTemplate.put(url, message);
    }

    public List<Message> getLast() {
        String url = "http://localhost:8080/api/last";

        String json = restTemplate.getForObject(url, String.class);
        return new Gson().fromJson(json, new TypeToken<List<Message>>(){}.getType());
    }
}

休息控制器

@org.springframework.web.bind.annotation.RestController
public class RestController {

    @Autowired
    TimerTask timerTask;

    @Resource
    private final MessageService messageService;

    public RestController(MessageService messageService) {
        this.messageService = messageService;
    }

    @PostMapping("/api/save")
    public ResponseEntity<String> saveMessage(@RequestBody Message chatMessage) {
        return messageService.add(chatMessage);
    }

    @GetMapping("/api/last")
    public String getLasts() {
        return new Gson().toJson(messageService.getLast());
    }

    @GetMapping("/api/unread")
    public void getUnreadMessages() {

        timerTask.run();
    }

    @GetMapping("/api/unread/{id}")
    public List<Message> getUnreadById(@PathVariable ("id") long id) {
        return messageService.getUnreadById(id);
    }

消息服务实现

@Service
@Transactional
public class MessageServiceImpl implements MessageService {
    private final MessageRepository repository;
    private final PageRequest lastRequest;

    private List<Long> chekedMessages = new ArrayList<>();


    @Autowired
    public MessageServiceImpl(MessageRepository repository) {
        this.repository = repository;
        lastRequest = new PageRequest(0, 10, Sort.Direction.DESC, "id");
    }

    @Override
    public ResponseEntity<String> add(@RequestBody  Message message) {
        try {
            message.setTime(new Timestamp(new Date().getTime()));
            repository.save(message);
            return new ResponseEntity<>("Сообщение сохранено", HttpStatus.OK);
        }catch (Exception e) {
         return new ResponseEntity<>(e.toString(), HttpStatus.CONFLICT);
        }
    }

    @Override
    public List<Message> getAllMessages() {
        return repository.findAll();
    }

    @Override
    public List<Message> getLast() {
        List<Message> result = repository.findAll(lastRequest).getContent();

        return result.stream()
                .sorted(Comparator.comparingLong(Message::getId))
                .collect(Collectors.toList());
    }

    @Override
    public List<Message> getUnreadById(long id) {
        return repository.getUnreadById(id);
    }



    @Override
    public String getUnreadMessages() {
        List<Message> out = new ArrayList<>();
        List<Message> unchekedMessages = repository.findAll();
        for (Message message: unchekedMessages) {
            if (!chekedMessages.contains(message.getId())) {
                chekedMessages.add(message.getId());
                out.add(message);
            }
        }
        return new Gson().toJson(out);
    }

    @Override
    public void updateMessage(long id, Message message) {
        if (repository.findById(id).isPresent()) {
            message.setId(id);
            repository.save(message);
        }
    }
}

标签: javajsonspringspring-boot

解决方案


尝试使用以下 curl 请求。

curl -X GET --header 'Accept: application/json'  'http://localhost:8080/api/unread/4'

推荐阅读