Rest call without RestTemplate - java

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?

Related

Calling multiple external APIs in Spring Boot

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?

Spring boot rest template - HttpMessageConverter cannot convert objects

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);

Class Cast Exception in REST call from android

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()

How to get the HTTP status of an API in spring boot when we hit it internally using Rest template

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());

Spring RestTemplate post response

I'm not familiar with Spring RestTemplate.
But for this project I have to use Spring RestTemplate to send a POST call to consume a rest api.
I'm using this code:
String restCall = restTemplate.postForObject(url+restParm, null, String.class);
This is working fine.
I would like to retriveve the HTTP status code (E.g: 200 OK.). How could I do that ?
Thanks.
You use the postForEntity method as follows...
ResponseEntity<String> response = restTemplate.postForEntity(url+restParm, null, String.class);
HttpStatus status = response.getStatusCode();
String restCall = response.getBody();
It will be pretty weird if RestTemplate couldn't get the response,as others have suggested. It is simply not true.
You just use the postForEntity method which returns a
http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/http/ResponseEntity.html
And as the documentation suggests, the response entity has the status.

Categories

Resources