I am trying a POST method with RestTemplate. I need my request to have only 1 query parameter, without body (e.g. localhost:8080/predictions/init?date=xxxx).
My current code is the following :
String url = "http://localhost:8080/predictions/init";
String dateToGenerate = "xxxx";
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("date", dateToGenerate);
HttpEntity<?> request = new HttpEntity<>(req_payload, headers);
restTemplateApi.postForEntity(url, request, String.class);
The side of the REST controller I'm trying to call is the following :
#PostMapping
#ResponseStatus(HttpStatus.OK)
public PredictionGenerated initializeOnePrediction(#RequestParam #NotEmpty String date) {
.............................
.............................
}
I'm currently receiving org.springframework.web.client.HttpClientErrorException: 400 null.
Any ideas?
If you have any many query param then set all in Multiple value Map as below.
MultiValueMap<String, String> param= new
LinkedMultiValueMap<String, String>();
param.put("date", datevalue);
Then create Http header add required content.
HttpHeaders headers = new HttpHeaders()
header.setContentType("application/json");
Create the URL as below.
URI url = UriComponentsBuilder.fromHttpUrl(base url)
.queryParams(param)
.build();
HttpEntity<?> request = new HttpEntity<>(req_payload,
headers);
restTemplateApi.postForEntity(url, request, String.class);
Related
I want to upload the file with Json request in rest template along with other properties. But I couldn't able to do this.
#Bean
public RestTemplate getRestTemplate(RestTemplateBuilder restTemplateBuilder) {
return restTemplateBuilder.build();
}
#Autowired
private RestTemplate restTemplate;
#Scheduled(fixedDelay = 1000)
public void _do() throws Exception {
HashMap<String, String> documentProperties = new HashMap<>();
documentProperties.put("number", "123");
MultipartFile file = Somefile;
UploadDocumentRequest uploadDocumentRequest = new UploadDocumentRequest();
uploadDocumentRequest.setDocumentClass("DocClass");
uploadDocumentRequest.setDocumentProperties(documentProperties);
uploadDocumentRequest.setFile(file); ----???
ResponseEntity<String> value = restTemplate.postForEntity("URL", uploadDocumentRequest, String.class);
}
You have to create HttpEntity with header and body.
Set the content-type header value to MediaType.MULTIPART_FORM_DATA.
Build the request body as an instance of LinkedMultiValueMap class.
Construct an HttpEntity instance that wraps the header and the body object and post it using a RestTemplate.
A sample code is shown as follows:
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("file", getFileToBeUploaded());
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.postForEntity(serviveUrl, requestEntity, String.class);
Here is my code: I have got xml file as output and i need to get one specific tag from that file
try {
RestTemplate restTemplate = new RestTemplate();
final String url = "https://wildfire.paloaltonetworks.com/publicapi/get/verdict";
String apikey = "f719c27d2063d2e25579681a64ebc1ba";
String hash = "a1a3b09875f9e9acade5623e1cca680009a6c9e0452489931cfa5b0041f4d290";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("apikey", apikey);
map.add("hash", hash);
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
ResponseEntity responseEntity = restTemplate.postForEntity("https://wildfire.paloaltonetworks.com/publicapi/get/verdict", request, String.class);
System.out.println(responseEntity);
The link below will show you how to convert your XML file (starting with either an XML file or XML String) into a Document.
https://howtodoinjava.com/xml/parse-string-to-xml-dom/
Once you have the document you can simply...
String tag = document.getDocumentElement().getAttribute("<TAG NAME>");
Hope this helps
I have a POST API written in Restlet framework which accepts the data in org.restlet.representation.Representation form, I want to hit the service with some variables and there values from Spring project. How to do that?
Right now I am using the HTTPHeaders to send the data but the API is not accepting the values, all the fields the API is showing as NULL. The code is as follows:
final String uri = "http://localhost:8080/MyServices/adduser";
String userid = "05580a6caa7244a6986ca834403f1a93";
String usertype = "buyer";
String username = "shivam42";
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.add("userid", userid);
headers.add("usertype", usertype);
headers.add("username", username);
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.POST, entity, String.class);
System.out.println(result);
And the service is like this:
#Post
public String newUser(Representation entity) {
Form form = new Form(entity);
String userid = form.getValues("userid");
String usertype = form.getValues("usertype");
String username = form.getValues("username");
System.out.println(userid);
System.out.println(usertype);
System.out.println(username);
return userid;
}
This is the code generated from curl Maybe someone can help me with this:
curl -X POST -H "Cache-Control: no-cache" -H "Postman-Token: 33e6a1c5-c1c9-694f-3d7f-26cbcea61870" -H "Content-Type: application/x-www-form-urlencoded" -d 'userid=05580a6caa7244a6986ca834403f1a93&usertype=buyer&username=shivam42' "http://localhost:8080/MyServices/adduser"
When I am calling the API from POSTMAN it is giving me the correct userid, now how to call it from Spring project? Am I doing something wrong?
#Shivam Thanks for updating the question. With the curl command in place I now see that the data you basically wanted to send is inside the request's body. Therefore the first approach with HttpHeaders won't work. Here's an example of how it could look like for your first approach using the exchange method of Springs RestTemplate:
#Test
public void test() {
RestTemplate restTemplate = new RestTemplate();
final String uri = "http://localhost:8080/adduser";
String userid = "05580a6caa7244a6986ca834403f1a93";
String usertype = "buyer";
String username = "shivam42";
// create request body
JSONObject request = new JSONObject();
request.put("userid", userid);
request.put("usertype", usertype);
request.put("username", username);
// set headers
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<>(request.toString(), headers);
ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.POST, entity, String.class);
System.out.println(result.getBody());
}
This should also work as expected and return the userid. See also POST request via RestTemplate in JSON for further information.
From the Spring forum I found the solution to this.
Now my code is:
final String uri = "http://localhost:8080/MyServices/adduser";
String userid = "05580a6caa7244a6986ca834403f1a93";
String usertype = "buyer";
String username = "shivam42";
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.add("userid", userid);
params.add("usertype", usertype);
params.add("username", username);
RestTemplate restTemplate = new RestTemplate();
HttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
HttpMessageConverter stringHttpMessageConverternew = new StringHttpMessageConverter();
List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
messageConverters.add(stringHttpMessageConverternew);
messageConverters.add(formHttpMessageConverter);
restTemplate.setMessageConverters(messageConverters);
System.out.println(restTemplate.postForObject(uri, params, String.class));
In my case I am also getting the expected result If I exclude the following code:
HttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
HttpMessageConverter stringHttpMessageConverternew = new StringHttpMessageConverter();
List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
messageConverters.add(stringHttpMessageConverternew);
messageConverters.add(formHttpMessageConverter);
restTemplate.setMessageConverters(messageConverters);
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);
I am trying to make a GET call to a url and I need to pass in queries to get the response i want.
I am using spring framework and using Rest template to make the calls.
I know i can manually do this way:
Uritemplate(url+name={name}...
but this is a pain. I need a easier way and the hash map will be generated dynamically
So how do i pass in a map to a url without using uri encoder?
String url = "example.com/search
Map<String, String> params = new HashMap<String, String>();
params.put("name", "john");
params.put("location", "africa");
public static ResponseEntity<String> callGetService(String url, Map<String, String> param) {
RestTemplate rest = new RestTemplate();
rest.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<?> reqentity = new HttpEntity<Object>(headers);
ResponseEntity<String> resp = rest.exchange(url, HttpMethod.GET, reqentity, String.class);
System.out.println(resp);
return resp;
}
So url will end up like this example.com/search?name=john&location=africa
response: {name:john doe, love: football} --- tons of json data
You can use UriComponentsBuilder and UriComponents which facilitate making URIs
String url = "http://example.com/search";
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.add("name", "john");
params.add("location", "africa");
UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(url).queryParams(params).build();
System.out.println(uriComponents.toUri());
prints
http://example.com/search?name=john&location=africa
There are other options if you need to use URI variables for path segments.
Note that if you are sending an HTTP request, you need an valid URL. The HTTP URL schema is explained in the HTTP specification, here.
The UriComponentsBuilder provides methods to build all parts of the URL.