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

编程入门 行业动态 更新时间:2024-10-28 08:17:36
本文介绍了如何使用 Spring RestTemplate POST 表单数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I want to convert the following (working) curl snippet to a RestTemplate call:

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

如何正确传递电子邮件参数?以下代码导致 404 Not Found 响应:

How do I pass the email parameter correctly? The following code results in a 404 Not Found response:

String url = "app.example/hr/email"; Map<String, String> params = new HashMap<String, String>(); params.put("email", "first.last@example"); RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> response = restTemplate.postForEntity( url, params, String.class );

我已经尝试在 PostMan 中制定正确的调用,并且可以通过将电子邮件参数指定为正文中的表单数据"参数来使其正常工作.在 RestTemplate 中实现此功能的正确方法是什么?

I've tried to formulate the correct call in PostMan, and I can get it working correctly by specifying the email parameter as a "form-data" parameter in the body. What is the correct way to achieve this functionality in a RestTemplate?

推荐答案

POST 方法应该与 HTTP 请求对象一起发送.并且请求可能包含 HTTP 标头或 HTTP 正文或两者.

The POST method should be sent along the HTTP request object. And the request may contain either of HTTP header or HTTP body or both.

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

Hence let's create an HTTP entity and send the headers and parameter in body.

HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>(); map.add("email", "first.last@example"); HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers); ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class );

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

更多推荐

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

本文发布于:2023-10-12 00:59:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1483322.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表单   如何使用   数据   RestTemplate   Spring

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!