gpt4 book ai didi

java - 如何使用 Spring RestTemplate POST 表单数据?

转载 作者:IT老高 更新时间:2023-10-28 11:20:32 34 4
gpt4 key购买 nike

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

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

如何正确传递 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 中实现此功能的正确方法是什么?

最佳答案

POST 方法应该随 HTTP 请求对象一起发送。并且请求可能包含 HTTP header 或 HTTP 正文或两者。

因此,让我们创建一个 HTTP 实体并在正文中发送 header 和参数。

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

关于java - 如何使用 Spring RestTemplate POST 表单数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38372422/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com