简体   繁体   中英

RestTemplate using to handle POST

I want to call a rest service in java code.My code as follows..


RestTemplate template = new RestTemplate();
TPOSBillDTO dto = new TPOSBillDTO();
dto.setId(1);

template.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
template.getMessageConverters().add(new StringHttpMessageConverter());
template.getMessageConverters().add(new FormHttpMessageConverter());

template.postForLocation("http://localhost:6458/games/toys",dto,String.class);

Below is my rest service

@RequestMapping(value = "/toys", method = RequestMethod.POST)
    public ModelAndView toys(@RequestParam TPOSBillDTO dto){
        Map<String, Object> model = new HashMap<String, Object>();

        System.out.println("Save Toy Details " + dto);

        return new ModelAndView("jsonView", model);
}

DTO class looks like this

public class TPOSBillDTO {

    private int id;
    private String name;
    private List<String> address;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<String> getAddress() {
        return address;
    }

    public void setAddress(List<String> address) {
        this.address = address;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}

Im getting an Exception as follows... Help me to solve this issue...

Is this the correct way to call a POST service with parameters .. This is working fine when im not accepting any parameters to the POST service...

Exception in thread "main" org.springframework.web.client.UnknownHttpStatusCodeException: Unknown status code [311] 311 at org.springframework.web.client.DefaultResponseErrorHandler.getHttpStatusCode(DefaultResponseErrorHandler.java:58) at org.springframework.web.client.DefaultResponseErrorHandler.hasError(DefaultResponseErrorHandler.java:49)

dto在请求正文中,不是作为您应使用的url参数发送的:

public ModelAndView toys(@RequestBody) TPOSBillDTO dto){

Have you tried to use "exchange" rather than "postForLocation"?
eg

template.exchange("http://localhost:6458/games/toys", dto, String.class);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM