Programing

Spring RestTemplate으로 양식 데이터를 POST하는 방법은 무엇입니까?

crosscheck 2020. 7. 19. 10:25

Spring RestTemplate으로 양식 데이터를 POST하는 방법은 무엇입니까?


다음 (작동) curl 스 니펫을 RestTemplate 호출로 변환하고 싶습니다.

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

이메일 매개 변수를 올바르게 전달하려면 어떻게합니까? 다음 코드는 404 Not Found 응답을 생성합니다.

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

Map<String, String> params = new HashMap<String, String>();
params.put("email", "first.last@example.com");

RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.postForEntity( url, params, String.class );

PostMan에서 올바른 호출을 공식화하려고 시도했으며 이메일 매개 변수를 본문에서 "form-data"매개 변수로 지정하여 올바르게 작동하도록 할 수 있습니다. RestTemplate에서이 기능을 수행하는 올바른 방법은 무엇입니까?


POST 메소드는 HTTP 요청 오브젝트와 함께 전송되어야합니다. 요청에는 HTTP 헤더 또는 HTTP 본문 또는 둘 다가 포함될 수 있습니다.

따라서 HTTP 엔터티를 만들고 본문에 헤더와 매개 변수를 보냅니다.

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. 클래스 -java.lang.Object ...-


혼합 데이터를 POST하는 방법 : File, String [], String in one request.

필요한 것만 사용할 수 있습니다.

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;
}

POST 요청은 파일에 Body와 다음 구조가 있습니다.

POST https://my_url?array=your_value1&array=your_value2&name=bob 

다음은 스프링의 RestTemplate을 사용하여 POST rest 호출을 수행하는 전체 프로그램입니다.

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());
    }

}

URL 문자열에는 다음과 같이 작업하기 위해 전달하는 맵에 변수 마커가 필요합니다.

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

또는 다음과 같이 쿼리 매개 변수를 명시 적으로 문자열로 코딩하여 맵을 전달할 필요가 없습니다.

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

참조 https://stackoverflow.com/a/47045624/1357094

참고 URL : https://stackoverflow.com/questions/38372422/how-to-post-form-data-with-spring-resttemplate