programing

Spring Rest Template로 폼 데이터를 POST하는 방법

prostudy 2022. 6. 6. 10:34
반응형

Spring Rest Template로 폼 데이터를 POST하는 방법

다음 (작업 중인) 컬 스니펫을 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에서 올바른 콜을 작성하려고 했습니다만, 본문의 「폼 데이터」파라미터로서 e-메일 파라미터를 지정하면 올바르게 동작할 수 있습니다.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.Class-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 요청의 본문과 다음 구조에 파일이 있습니다.

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

스프링의 RestTemplate를 사용하여 POST를 호출하는 전체 프로그램입니다.

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

}

Client.java

@PostMapping(value = "/employee", consumes = "application/json")
public Employee createProducts(@RequestBody Employee product) {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    HttpEntity<Employee> entity = new HttpEntity<Employee>(product,headers);

    ResponseEntity<Employee> response = restTemplate.exchange(
            "http://hello-server/rest/employee", HttpMethod.POST, entity, Employee.class);

    return response.getBody();
}

Server.java

private static List<Employee> list = new ArrayList<>();

@PostMapping(path="rest/employee", consumes = "application/json")
public Employee createEmployee(@RequestBody Employee employee)

{
    list.add(employee);
    return employee;
}
static
{
    list.add(new Employee(1, "albert", "Associate", "mphasis"));
    list.add(new Employee(2, "sachin", "software engineer", "mphasis"));
    list.add(new Employee(3, "dhilip", "Lead engineer", "IBM"));
}

직원.자바

public class Employee {

private Integer id;
private String name;
private String Designation;
private String company;
 // generate getter setter and toString()
}

1. 포스트 리퀘스트

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

반응형