Java 如何使用 Spring RestTemplate POST 表单数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38372422/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to POST form data with Spring RestTemplate?
提问by sim
I want to convert the following (working) curl snippet to a RestTemplate call:
我想将以下(工作)curl 片段转换为 RestTemplate 调用:
curl -i -X POST -d "[email protected]" https://app.example.com/hr/email
How do I pass the email parameter correctly? The following code results in a 404 Not Found response:
如何正确传递电子邮件参数?以下代码导致 404 Not Found 响应:
String url = "https://app.example.com/hr/email";
Map<String, String> params = new HashMap<String, String>();
params.put("email", "[email protected]");
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.postForEntity( url, params, String.class );
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?
我尝试在 PostMan 中制定正确的调用,并且可以通过将 email 参数指定为正文中的“form-data”参数来使其正常工作。在 RestTemplate 中实现此功能的正确方法是什么?
采纳答案by Tharsan Sivakumar
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.
POST 方法应该与 HTTP 请求对象一起发送。并且请求可能包含 HTTP 标头或 HTTP 正文或两者。
Hence let's create an HTTP entity and send the headers and parameter in body.
因此,让我们创建一个 HTTP 实体并在正文中发送标头和参数。
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
map.add("email", "[email protected]");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class );
回答by Piyush Mittal
here is the full program to make a POST rest call using spring's RestTemplate.
这是使用 spring 的 RestTemplate 进行 POST 休息调用的完整程序。
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import com.ituple.common.dto.ServiceResponse;
public class PostRequestMain {
public static void main(String[] args) {
// TODO Auto-generated method stub
MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
Map map = new HashMap<String, String>();
map.put("Content-Type", "application/json");
headers.setAll(map);
Map req_payload = new HashMap();
req_payload.put("name", "piyush");
HttpEntity<?> request = new HttpEntity<>(req_payload, headers);
String url = "http://localhost:8080/xxx/xxx/";
ResponseEntity<?> response = new RestTemplate().postForEntity(url, request, String.class);
ServiceResponse entityResponse = (ServiceResponse) response.getBody();
System.out.println(entityResponse.getData());
}
}
回答by Yuliia Ashomok
How to POST mixed data: File, String[], String in one request.
如何在一个请求中发布混合数据:文件、字符串[]、字符串。
You can use only what you need.
您可以只使用您需要的东西。
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;
}
The POST request will have File in its Body and next structure:
POST 请求的正文和下一个结构中将包含 File:
POST https://my_url?array=your_value1&array=your_value2&name=bob
回答by cellepo
Your url String needs variable markers for the map you pass to work, like:
您的 url 字符串需要您传递的地图的变量标记,例如:
String url = "https://app.example.com/hr/email?{email}";
Or you could explicitly code the query params into the String to begin with and not have to pass the map at all, like:
或者,您可以将查询参数显式编码到字符串中以开始,而根本不必传递地图,例如:
String url = "https://app.example.com/hr/[email protected]";