如何使用Spring RestTemplate发布表单数据?

2022-08-31 05:56:13

我想将以下(工作)curl代码段转换为 RestTemplate 调用:

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

如何正确传递电子邮件参数?下面的代码导致 404 未找到响应:

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中制定正确的调用,并且可以通过在正文中将电子邮件参数指定为“表单数据”参数来使其正常工作。在 RestTemplate 中实现此功能的正确方法是什么?


答案 1

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...-


答案 2

如何发布混合数据:文件,字符串[],一个请求中的字符串。

您只能使用所需的内容。

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