How to POST form data with Spring RestTemplate?

前端 未结 4 1123
栀梦
栀梦 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:14

    here is the full program to make a POST rest call using spring's RestTemplate.

    import java.util.HashMap;
    import java.util.Map;
    
    import org.springframework.http.HttpEntity;
    import org.springframework.http.ResponseEntity;
    import org.springframework.util.LinkedMultiValueMap;
    import org.springframework.util.MultiValueMap;
    import org.springframework.web.client.RestTemplate;
    
    import com.ituple.common.dto.ServiceResponse;
    
       public class PostRequestMain {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
            Map map = new HashMap<String, String>();
            map.put("Content-Type", "application/json");
    
            headers.setAll(map);
    
            Map req_payload = new HashMap();
            req_payload.put("name", "piyush");
    
            HttpEntity<?> request = new HttpEntity<>(req_payload, headers);
            String url = "http://localhost:8080/xxx/xxx/";
    
            ResponseEntity<?> response = new RestTemplate().postForEntity(url, request, String.class);
            ServiceResponse entityResponse = (ServiceResponse) response.getBody();
            System.out.println(entityResponse.getData());
        }
    
    }
    
    0 讨论(0)
  • 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<String, String> map= new LinkedMultiValueMap<String, String>();
    map.add("email", "first.last@example.com");
    
    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
    
    ResponseEntity<String> 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...-

    0 讨论(0)
  • 2020-11-29 17:31

    Your url String needs variable markers for the map you pass to work, like:

    String url = "https://app.example.com/hr/email?{email}";
    

    Or you could explicitly code the query params into the String to begin with and not have to pass the map at all, like:

    String url = "https://app.example.com/hr/email?email=first.last@example.com";
    

    See also https://stackoverflow.com/a/47045624/1357094

    0 讨论(0)
  • 2020-11-29 17:37

    How to POST mixed data: File, String[], String in one request.

    You can use only what you need.

    private String doPOST(File file, String[] array, String name) {
        RestTemplate restTemplate = new RestTemplate(true);
    
        //add file
        LinkedMultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        params.add("file", new FileSystemResource(file));
    
        //add array
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("https://my_url");
        for (String item : array) {
            builder.queryParam("array", item);
        }
    
        //add some String
        builder.queryParam("name", name);
    
        //another staff
        String result = "";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
    
        HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity =
                new HttpEntity<>(params, headers);
    
        ResponseEntity<String> responseEntity = restTemplate.exchange(
                builder.build().encode().toUri(),
                HttpMethod.POST,
                requestEntity,
                String.class);
    
        HttpStatus statusCode = responseEntity.getStatusCode();
        if (statusCode == HttpStatus.ACCEPTED) {
            result = responseEntity.getBody();
        }
        return result;
    }
    

    The POST request will have File in its Body and next structure:

    POST https://my_url?array=your_value1&array=your_value2&name=bob 
    
    0 讨论(0)
提交回复
热议问题