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 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:
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 ...
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
. 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With