Java 如何使用标头中的自定义参数通过 RestTemplate 发送 POST 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28346255/
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 send POST request through RestTemplate with custom parameter in header
提问by Asalas77
I need to send post request with custom parameter("data" containing path) and set content type as 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 MappingHymanson2HttpMessageConverter());
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.
提前致谢。
采纳答案by nilesh
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
. Just try sending a string,
从评论中的讨论来看,很明显您的请求对象不正确。如果您要传递包含文件夹名称的纯字符串,则不需要MultiValueMap
. 尝试发送一个字符串,
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 MappingHymanson2HttpMessageConverter());
String response = restTemplate
.postForObject(url, request, String.class);