简体   繁体   中英

JSON contents answered from an API returns null (with Spring boot)

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.accC[.[.[/].[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?

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: 在此处输入图像描述

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM