How to POST form data with Spring RestTemplate?

前端 未结 4 1137
栀梦
栀梦 2020-11-29 16:57

I want to convert the following (working) curl snippet to a RestTemplate call:

curl -i -X POST -d \"email=first.last@example.com\" https://app.example.com/hr         


        
4条回答
  •  温柔的废话
    2020-11-29 17:22

    The POST method should be sent along the HTTP request object. And the request may contain either of HTTP header or HTTP body or both.

    Hence let's create an HTTP entity and send the headers and parameter in body.

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    
    MultiValueMap map= new LinkedMultiValueMap();
    map.add("email", "first.last@example.com");
    
    HttpEntity> request = new HttpEntity>(map, headers);
    
    ResponseEntity response = restTemplate.postForEntity( url, request , String.class );
    

    http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html#postForObject-java.lang.String-java.lang.Object-java.lang.Class-java.lang.Object...-

提交回复
热议问题