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

新手上路,请多包涵

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

原文由 sim 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 665
2 个回答

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

原文由 Tharsan Sivakumar 发布,翻译遵循 CC BY-SA 3.0 许可协议

如何 POST 混合数据:File、String[]、String 在一个请求中。

您可以只使用您需要的东西。

 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 和下一个结构中包含 File:

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

原文由 Yuliia Ashomok 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题