如何使用 Spring RestTemplate POST 表单数据? [英] How to POST form data with Spring RestTemplate?

查看:34
本文介绍了如何使用 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.com" https://app.example.com/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 = "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 中实现此功能的正确方法是什么?

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

这篇关于如何使用 Spring RestTemplate POST 表单数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆