" org.springframework.web.client.HttpClientErrorException:400 Bad Request"使用" RestTemplate.put()"

时间:2015-08-17 20:59:54

标签: java spring web-services spring-mvc

我使用Spring Data MVC编写了这个Web服务:

休息控制器

@RestController
@RequestMapping("/textmessages")
public class TextMessageRestController {

    @Autowired
    private TextMessageService textMessageService;


    @RequestMapping(value = "/send", method = RequestMethod.PUT)
    @ResponseStatus(HttpStatus.CREATED)
    public void insertTextMessage(@RequestBody TextMessage.TextMessageDTO textMessageDTO) {
        textMessageService.save(textMessageDTO);
    }
}

春季服务

@Service
@Transactional
public class TextMessageService {

    @Autowired
    private TextMessageRepository textMessageRepository;
    @Autowired
    private UserService userService;

    public void save(TextMessage message) {
        textMessageRepository.save(message);
    }


    public void save(TextMessage.TextMessageDTO textMessageDTO) {
        save(from(textMessageDTO));
    }

    public TextMessage from(TextMessage.TextMessageDTO textMessageDTO) {
        User sender = userService.from(textMessageDTO.getSender());
        User receiver = userService.from(textMessageDTO.getReceiver());
        return new TextMessage(receiver, sender, textMessageDTO.getSymmetricKeyEncrypted(), textMessageDTO.getText());
    }
}

DTO - 静态内部类

//This annotations are from Lombok
@Getter
@Setter
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public static class SenderReceiverDTO {
    private String username;
    private String pk;

    public static SenderReceiverDTO from(User user) {
        SenderReceiverDTO dto = new SenderReceiverDTO(user.username, user.pk);
        return dto;
    }
}

当我尝试使用该REST服务时,我得到以下异常:

消耗休息服务

public class RestService {
    private static final String REST_STRING = "http://localhost:8080/cchat/";
    private static final String TXT_MSG_STRING = REST_STRING + "textmessages/";
    private static final String SEND_TXT_MSG = TXT_MSG_STRING + "send/";
    private final RestTemplate restTemplate;

    public RestService() {
        this.restTemplate = new RestTemplate();
    }

    @SuppressWarnings("unchecked")
    public List<TextMessage.TextMessageDTO> loadTextMessages(User.UserIdentifyingDTO userIdentifyingDTO) {
        return restTemplate.postForObject(RECEIVE_TXT_MSG, userIdentifyingDTO, List.class);
    }
}

我得到了解雇

org.springframework.web.client.HttpClientErrorException: 400 Bad Request
at foo.RestService.sendTextMessage(RestService.java:33)

测试证明服务器端工作正常! 什么可能导致问题的想法?

0 个答案:

没有答案