Home > Software engineering >  JSON contents answered from an API returns null (with Spring boot)
JSON contents answered from an API returns null (with Spring boot)

Time:07-12

I'm learning to consume API with Spring boot and faced the following problem:

The URL "http://servicebus2.caixa.gov.br/portaldeloterias/api/home/ultimos-resultados" returns a JSON with the last results from Brazil's Lottery.

When trying to receive this output with a Spring controller:

@GetMapping(value = "/loterias")
public String getLotteryResults() {
    String url = "http://servicebus2.caixa.gov.br/portaldeloterias/api/home/ultimos-resultados";
    RestTemplate rest = new RestTemplate();
    Object results = rest.getForObject(url, Object.class);

    return results.toString();

I receive the following error message:

2022-07-10 12:22:14.692[0;39m [31mERROR[0;39m [35m17456[0;39m [2m---[0;39m [2m[nio-8080-exec-1][0;39m [36mo.a.c.c.C.[.[.[/].[dispatcherServlet] [0;39m [2m:[0;39m Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException: Cannot invoke "Object.toString()" because "results" is null] with root cause

I'm following the tutorial from "https://www.geeksforgeeks.org/how-to-call-or-consume-external-api-in-spring-boot/" (it works using the new link "https://restcountries.com/v3.1/all").

I had already tried the same output class as in the example with no success... Any hints on what can be done in this case?

CodePudding user response:

It seems that the link you posted is not active anymore "http://servicebus2.caixa.gov.br/portaldeloterias/api/home/ultimos-resultados"

on chrome it sends a redirection to it's https endpoint: enter image description here

When tried using restTemplate.getForEntity(url, Object.class) it shows a 302-redirect, modern browsers will automatically redirect hence it's transparent for the user.

<302,[Location:"https://servicebus2.caixa.gov.br/portaldeloterias/api/home/ultimos-resultados", Connection:"close"]>

Try to directly use its https endpoint, but this also means you need to handle the security certs guide

  • Related