How to POST form data with Spring RestTemplate?

前端 未结 4 1149
栀梦
栀梦 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 headers = new LinkedMultiValueMap();
            Map map = new HashMap();
            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());
        }
    
    }
    

提交回复
热议问题