I have a REST API with this endpoint:
#GET
#Path("rol/{codEmp}")
#Produces(MediaType.TEXT_PLAIN)
public String getRole(#PathParam("codEmp") Long codEmp) {
return dao.getRole(codEmp);
}
An example of response can be: HOUSEKEEPER.
I consume it this way:
#Override
public String getRole(Long codEmp) {
HashMap<String, Object> urlVariables = new HashMap<String, Object>();
urlVariables.put("codEmp", codEmp);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setAccept(Collections.singletonList(MediaType.parseMediaType("text/plain")));
HttpEntity<Object> requestEntity = new HttpEntity<Object>(httpHeaders);
return restTemplate.exchange(rootUrl.concat("/rol/{codEmp}"), HttpMethod.GET, requestEntity, String.class, urlVariables).getBody();
}
But I get this error:
"Could not extract response: no suitable HttpMessageConverter found
for response type [java.lang.String] and content type [text/plain]"
I know the right way is to send a JSON response but I have to do it with raw String.
How can I solve it?
Thanks
Solved. I have added an String converter to my Rest Template:
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
Related
I have 2 spring boot apps running one as a frontend and another as a backend service. From the frontend i make an api call to the backend service and both the parameters that i send show up as null. I think the problem is in the rest template.
UPDATE
So i have noticed if i omit the content value then it works. Since content is the content of a file that is larger than 1mb I added the following to application.yml:
spring.servlet.multipart.max-file-size: 10MB
spring.servlet.multipart.max-request-size: 10MB
Here is my code which I updated from one posted in this issue:
How to POST form data with Spring RestTemplate?
But i still don't get the value in the backend controller instead both values are null.
public void upload(byte[] content, String name) {
String encodedString = Base64.getEncoder().encodeToString(content);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("fileName", name);
map.add("content", encodedString);
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
ResponseEntity<String> response = restTemplate.postForEntity(backendUrl + "/upload", request, String.class);
log.debug("Response from upload: " + response);
}
And here is the controller in the backend. Both fileName and content are null:
#CrossOrigin
#SneakyThrows
#ResponseBody
#PostMapping(value = "/upload")
public ResponseEntity<String> upload(#ModelAttribute FormModel form) {
byte[] decodedBytes = Base64.getDecoder().decode(form.getContent());
uploadService.upload(decodedBytes, form.getFileName());
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("Content-Type", "application/json");
return ResponseEntity.ok().headers(responseHeaders).body("Uploaded");
}
Can anyone please see what is wrong with this code?
Thanks in advance.
I guess the problem is that you are trying to use restTemplate.postForObject but with #RequestParam and not a #RequestBody.
In #RequestParam you are expecting the data to be received in the query params /upload?fileName=&content=. But you are actually sending it in the body with the restTemplate.postForObject(backendService+ "/upload", map, String.class);.
So my suggestion is to change
public ResponseEntity<String> upload(#RequestParam(value = "fileName") String fileName, #RequestParam(value = "content") String content)
to
public ResponseEntity<String> upload(#RequestBody Map<String, String> body)
and then get fileName and fileContent from the body.
Ok i could fix it by sending and receiving bytes instead of bytes encoded as string.
So in the resttemplate:
public void upload(byte[] bytes, String name) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
map.add("fileName", name);
map.add("bytes", bytes);
HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<MultiValueMap<String, Object>>(map, headers);
log.debug("map values: " + map.toString());
ResponseEntity<String> response = restTemplate.postForEntity(backendUrl + "/upload", request, String.class);
log.debug("Response from upload: " + response);
}
And in the controller:
public ResponseEntity<String> upload(#ModelAttribute FormModel form) {
byte[] bytes = form.getBytes();
uploadService.upload(bytes, form.getFileName());
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("Content-Type", "application/json");
return ResponseEntity.ok().headers(responseHeaders).body("Uploaded");
}
Still it would be good to know why the previous version didn't work.
I have this method to make request:
#Override
public HttpEntity<MultiValueMap<String, String>> generateRequestEntity(Date date) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("key", "SOME_API_KEY");
map.add("source", "SOME_API_SOURCE");
if (date == null)
map.add("method", "getall");
else {
map.add("method", "getfrom");
map.add("date", new SimpleDateFormat("yyyy-MM-dd").format(date));
}
return new HttpEntity<>(map, headers);
}
I send a request and get a response, as recommended at following link: URL
HttpEntity<MultiValueMap<String, String>> request = generateRequestEntity(date);
ResponseEntity<OnlineSell[]> response = restTemplate.postForEntity(url, request, OnlineSell[].class);
OnlineSell[] onlineSells = response.getBody();
But I have a problem. I am failing when trying to parse JSON-response. OnlineSell - class, that must keep the answer BUT I just can’t create a structure that successfully stores the values of this answer. A very large and complex answer tree comes.
Answer: Can I get JSONObject from it to parse and save manually? Or can I get help with JSON parsing by previously updating this post and adding it (answer form Postman)?
What you can do is to consider the ResponseEntity as a String.
Then afterwards you can use objectMapper with readValue(),
Something like this:
ResponseEntity<String> response = restTemplate().postForEntity(url, request, String.class);
String body = response.getBody();
OnlineSell[] onlineSells = new ObjectMapper().readValue(body, OnlineSell[].class);
i'm trying to retrieve an put api exposed response as a Response object
the valid url http://localhost:8081/nameoftheapplication*/{id}/validateToExportFile
the return format example when i tested it is like :
i'm using restTemplate exchange because the put just do the update,the method works fine when i change the return type to String but i want to return a Response for other treatment the method that i'm using actually is
public Response validateToExportFileExchange(ReturnValidationDetails returnValidationDetails) {
String validationURL = (validateToExportURI + "/" + returnValidationDetails.getReturnId() + "/validateToExportFile");
HttpHeaders headers = new HttpHeaders();
headers.add("Accept", "*/*");
List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8));
messageConverters.add(converter);
resttemplate.setMessageConverters(messageConverters);
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
HttpEntity<ReturnValidationDetails> validateToExportFileExchangeEntity = new HttpEntity<>(returnValidationDetails, headers);
return resttemplate.exchange(validationURL, HttpMethod.PUT, validateToExportFileExchangeEntity,
Response.class).getBody();
}
and i have this Exception :
Could not extract response: no suitable HttpMessageConverter found for response type [interface javax.xml.ws.Response] and content type [application/vnd.openxmlformats-officedocument.spreadsheetml.sheet]
thx in advance for your help
Can some one tell me how to send a POST request with raw data parameters as in the picture below
i have tried the following code but its not working
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
JsonObject properties = new JsonObject();
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
try {
properties.addProperty("app_id", appId);
properties.addProperty("identity","TestAPI");
properties.addProperty("event", "TestCompleted");
properties.addProperty("testType", t.getTestType());
properties.addProperty("testName",t.getTestName());
properties.addProperty("chapter","");
properties.addProperty("module","");
properties.addProperty("pattern",t.getTestPattern());
HttpEntity<String> request = new HttpEntity<>(
properties.toString(), headers);
// params.add("properties", properties.toString());
restTemplate.postForObject(url, request, String.class);
can someone help?
Try this :
#RestController
public class SampleController {
#RequestMapping("/req")
public String performReqest(){
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
JsonObject properties = new JsonObject();
properties.addProperty("no", "123");
properties.addProperty("name", "stackoverflow");
HttpEntity<String> request = new HttpEntity<>(properties.toString(), headers);
RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.postForObject("http://localhost:4040/student", request, String.class);
return "Response from Server is : "+response;
}
#RequestMapping("/student")
public String consumeStudent(#RequestBody Student student){
System.out.println(student);
return "Hello.."+student.name;
}
}
class Student{
public int no;
public String name;
public Map<String,String> properties;
}
Don't forgot to move Student class and change all field to private with require getters and setters.
Above code is only for demo purpose.
Please try with this:
ResponseEntity<String> result = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
Did u tried using postmaster and checked the output first. If its working then you can go for post or exchange method. exchange returns and post dont.
try this:
URI uri = new URI("something");
Map<String, Object> params = new HashMap<>();
params.put("app_id", "something");
params.put("identity", something);
HttpEntity<Map<String, String>> request = new HttpEntity(params , headers);
ResponseEntity<String> response = restTemplate.postForEntity(uri, request, String.class);
I have added Dependency for Gson in pom.xml
public ResponseEntity<String> findSearchInfo(#RequestParam String searchName)
{
ResponseEntity<String> response = gasRESTTemplate
.getForEntity(uri,String.class);
Gson gson = new Gson();
response = gson.toJson(response);
return response;
}
uri is returning me a HashMap which I want to convert to JSON.So I have used Gson's toJson method.Now the problem is that method is returning me json but i am unable to assign it to response cause it's type is ResponseEntity which is compulsory.
So what should I do to return that json by response?
Because of this I am getting error
required: org.springfremwork.http.ResponseEntity<java.lang.String>
found: java.lang.String
I know return type is ResponseEntity
So How should I initialize that JSON to response variable.
What about using this constructor (source) :
ResponseEntity(T body, MultiValueMap<String,String> headers, HttpStatus statusCode)
ResponseEntity<String> response =
new ResponseEntity(gson.toString(),
new MultiValueMap(),
HttpStatus.OK);