[英]How to send POST request through RestTemplate with custom parameter in header
I need to send post request with custom parameter("data" containing path) and set content type as text/plain. 我需要使用自定义参数(“data”包含路径)发送post请求,并将内容类型设置为text / plain。 I looked through a ton of similar question but none of the solutions posted helped. 我查看了大量类似的问题,但没有一个解决方案有帮助。
The method should list files from this directory. 该方法应列出此目录中的文件。
my code is 我的代码是
public List<FileWrapper> getFileList() {
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("data", "/public/");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(
map, headers);
String url = "http://192.168.1.51:8080/pi/FilesServlet";
restTemplate.getMessageConverters().add(new FormHttpMessageConverter());
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
String response = restTemplate
.postForObject(url, request, String.class);
List<FileWrapper> list = new ArrayList<>();
for (String part : response.split("\\|")) {
System.out.println("part " + part);
list.add(new FileWrapper(part));
}
return list;
}
Here's working code equivalent written in javascript: 这是用javascript编写的等效工作代码:
function getFileList(direction){
$("div.file-list").html("<center><progress></progress></center>");
$.ajax({
url: "http://192.168.1.51:8080/pi/FilesServlet",
type: "POST",
data: direction ,
contentType: "text/plain"
})
The parameter is not added as the request returns empty string meaning the path is not valid. 由于请求返回空字符串意味着路径无效,因此不会添加该参数。 The expected response is file_name*file_size|file_name*file_size ...
预期的响应是file_name*file_size|file_name*file_size ...
Thanks in advance. 提前致谢。
From the discussion in the comments, it's quite clear that your request object isn't correct. 从评论中的讨论来看,很明显您的请求对象不正确。 If you are passing a plain string containing folder name, then you don't need a MultiValueMap
. 如果要传递包含文件夹名称的纯字符串,则不需要MultiValueMap
。 Just try sending a string, 试试发一个字符串,
String data = "/public/"
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
HttpEntity<String> request = new HttpEntity<String>(
data, headers);
String url = "http://192.168.1.51:8080/pi/FilesServlet";
restTemplate.getMessageConverters().add(new FormHttpMessageConverter());
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
String response = restTemplate
.postForObject(url, request, String.class);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.