I am trying to get List of items from my web application MyApp running on server server 172.16.xx.15 from my android app using resttemplate.
Everything works fine when I do like
String url="http://172.16.xx.15:8080/MyApp/GetAllItem";
RestTemplate restTemplate=new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
List<LinkedHashMap> items=restTemplate.getForObject(url, List.class);
Above code works fine when I make above url access anonymously. But I am using spring security at server end, I need to authenticate user before accessing this list of items. So I am trying to get same list of items with authentication. I am using following code:
String username="test"
String password="test"
HttpAuthentication authHeader=new HttpBasicAuthentication(username, password)
HttpHeaders requestHeaders=new HttpHeaders();
requestHeaders.setAuthorization(authHeader);
requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON);
RestTemplate restTemplate=new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
List<LinkedHashMap> items=(List<LinkedHashMap>)restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<Object>(requestHeaders), List.class);
This code also works somewhat but throwing error and application crashing.
java.lang.ClassCastException:org.springframework.http.ResponseEntity
cannot be cast to java.util.List
please help in this situation.
You are directly casting the response of exchange which is ResponseEntity into your collection
You need to collect first as
ReaponseEntity<List<LinkedHashMap>> response
Then on above call the
response.getBody()
List<LinkedHashMap> items=(List<LinkedHashMap>)restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<Object>(requestHeaders), List.class);
restTemplate.exchange method returns a ResponseEntity<T> object so it is absolutely normal to get the ClassCastException. You need to rewrite your above line to something like this:
ResponseEntity<<LinkedHashMap>> entity = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<Object>(requestHeaders), List.class);
List<LinkedHashMap> items = entity.getBody()
Related
I am working on a project but it requires me to call multiple external APIs. I basically have to call an API to get a player id by giving a name. Then use that player id to get a list of match ids. Then make calls for each match id to get details on each match. its alot and doesnt seem optimal but its the only way to do it. I was going to use rest template to make a call to the following
https://americas.api.riotgames.com/lol/match/v5/matches/by-puuid/HDzjdaStxhHcceGGd8qJcc4Vw45FOlOQ1PNXKQ0h9_iqfwHP3oI0spl1bLUOw_7_J49vzaIKylv5Vg/ids?start=0&count=20
I have to pass in headers as well such as
riot token : token
"Origin": "https://developer.riotgames.com"
I was wondering how I can do this in Java Spring boot. I saw RestTemplate would be used but I couldnt figure out how to include the headers. Any guidance would be appreciated.
You can call RestTemplate.exchange() using either the method signature with RequestEntity or with HttpEntity.
// Using RequestEntity
RequestEntity<?> request= RequestEntity.get(url).header(headerName, headerValue).build();
ResponseEntity<String> response = restTemplate.exchange(request, String.class);
// Using HttpEntity
HttpHeaders headers = new HttpHeaders();
headers.set(headerName, headerValue);
HttpEntity httpEntity = new HttpEntity(/* this is nullable */ requestBody, headers);
ResponseEntity,String> response = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
Would also recommend reading through the following:
https://howtodoinjava.com/spring-boot2/resttemplate/spring-restful-client-resttemplate-example/
https://www.baeldung.com/rest-template
How to set an "Accept:" header on Spring RestTemplate request?
I have a url generated by a GET method which is somewhat of this format:
https://service-name/api?param1=<value1>¶m2=<value2>¶m3=<value3>.....
I need to hit this url and store the response (which will be of type application/x-www-form-urlencoded) into a variable, which will be used further.
The issue is that it needs to be done inside the method (get the url and pass it to get a response).
How to go about it?
For a spring boot application to consume an external API, you can use RestTemplate.
An example of usage is below. The response you receive is of type String.
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.add("Header", "header1");
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("https://foo/api/v3/projects/1/labels")
.queryParam("param1", param1)
.queryParam("param2", param2);
HttpEntity<?> entity = new HttpEntity<>(headers);
HttpEntity<String> response = restTemplate.exchange(
builder.toUriString(),
HttpMethod.GET,
entity,
String.class);
hello everyone I have a problem that I do not understand why this is happening. I am working with spring boot and deploying with Kubernetes. after a while, the restTemplate stops working and I do not know what can be the cause. this is how I am creating the restTemplate class
#Bean
public RestTemplate vanillaRestTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setErrorHandler(new RestTemplateErrorHandler());
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
return restTemplate;
}
after a while some of my APIs that is using restTemplate returns an error like this:
{
"status": 500,
"body": "{ message: Could not extract response: no suitable HttpMessageConverter found for response type [interface java.util.List] and content type [application/json;charset=UTF-8] , cause: null }",
}
this is only an example. resttemplate will have a problem with many classes such as Map, String, etc when this happens. and this is how I am sending the request:
ResponseEntity<List> adsRes = restTemplate.getForEntity(url, List.class);
the weird part is when I restart the app on the server everything starts working again and the APIs have no problem at all. even the ones that returned an error.
I have read this question but, as you can see I have not set any interceptor or anything like that to resttemplate
thanks in advance
Try replace the way how you are calling to the endpoint by the following code
ResponseEntity<YourObject[]> response = restTemplate.getForEntity("urlService",
YourObject[].class);
YourObject[] yourObjects= response.getBody();
List<YourObject> list = Arrays.asList(yourObjects);
WebSphere don't load previous classes (com.fasterxml.jackson.core.JsonGenerator and com.fasterxml.jackson.databind.ObjectMapper) of RestTemplate for do a REST call with customize class to catch JSON in response.
Now I'm trying to find an alternative to RestTemplate for do REST call.
Anyone have an idea?
This is my actually code but don't load previous classes so don't match JSON
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Person> restResponse = restTemplate.getForEntity(providerUrl, Person.class);
Did you consider the following:
ResponseEntity<String> restResponse = restTemplate.getForEntity(providerUrl, String.class);
Then parse the response body yourself?
I want to get the object as well as the HTTP response of one api into another in Spring code. For that I am using a rest template and I am getting the desired Object from it successfully.
But I want to fetch HTTP response also for the respective api.
What should I do to get this?
RestTemplate restTemplate = new RestTemplate();
Quote quote = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", Quote.class);
System.out.println("quote "+quote);
System.out.println(quote.getType());
log.info(quote.toString());
getForObject method of RestTemplate only gets the result. If you're interest in the status code you should invode exchange which returns a ResponseEntity which has a getStatusCode method.
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Quote> response= restTemplate.exchange ("http://gturnquist-quoters.cfapps.io/api/random", HttpMethod.GET, null, Quote.class);
Quote quote = response..getBody();
System.out.println("status "+response..getStatusCode());
System.out.println("quote "+quote);
System.out.println(quote.getType());