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

查看:157
本文介绍了如何使用Spring RestTemplate发布表单数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将以下(工作)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?

推荐答案

应该沿HTTP请求对象发送POST方法。并且请求可以包含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发布表单数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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