Weather API - Cities with accent give error

Asked

Viewed 664 times

4

I have the following Endpoint in which you receive in the URI the name of the city and the state:

@RequestMapping(value= "/clima/{nomeCidade}/{ufCidade}/agora",  method = {RequestMethod.GET, RequestMethod.OPTIONS} , produces="application/json" )
public ResponseEntity<Clima> getClimaAgoraByNomeCidade(@PathVariable(value = "nomeCidade") String nomeCidade,  @PathVariable(value = "ufCidade") Estado ufCidade) throws JSONException, ParseException, java.text.ParseException {

    JSONObject detCidade = new JSONObject();
    ClimaTempoAPI ct = new ClimaTempoAPI();     

    String newNomeCidade = nomeCidade.toLowerCase().replace(" ", "%20");
    String weatherEndpoint = "/api/v1/locale/city?name=" + newNomeCidade + "&state=" + ufCidade.toString();
    Long idCidade;

    Integer findRegCidade = climaRepository.findCountCidade(ufCidade, nomeCidade);

    // Se a cidade existir no banco
    if(findRegCidade != 0) {

        // Atribuir o idCidade da cidade e fazer requisi�ao no banco
        idCidade = climaRepository.findTop1IdCidade(ufCidade, nomeCidade);

    // Se nao existir a cidade no banco, gravar a cidade e fazer a requisicao   
    } else {

        try {
            detCidade = ct.RequestWeather(weatherEndpoint);
        } catch (IOException e) {
            e.printStackTrace();
        }

        CidadeCT cidadeCT = new CidadeCT();
        cidadeCT.setId((long) System.currentTimeMillis());
        cidadeCT.setCodPais(detCidade.get("country").toString().trim());
        cidadeCT.setNomeCidade((String) detCidade.get("name"));
        idCidade = (Long) detCidade.get("id");
        cidadeCT.setIdCidade(idCidade);
        cidadeCT.setEstado(Enum.valueOf(Estado.class, detCidade.get("state").toString()));  
        cidadeCTRepository.save(cidadeCT);  

    }       

    return getClimaAgora(idCidade);


}

Requestweather() method is as follows::

public JSONObject RequestWeather(String weatherEndpoint) throws IOException, JSONException, ParseException {

    String appToken = "&token=xxx";     

    URL weatherDomain = new URL("http://apiadvisor.climatempo.com.br" + weatherEndpoint + appToken);

    return ConnectionJson.returnJson(weatherDomain, true);

}

And my AJAX call on the Front-End . js is as follows:

var uf = $("#colWeather #selectState").val();
var city = $("#colWeather #selectCity").val();    

//Send a request to the ClimaTempo Endpoint
$.ajax({
    url: host + '/clima/' + city + '/' + uf + '/agora',
    type: 'GET',
    contentType: "application/json",
    async: true
}).done(function (JSONReturn) {

      //Algumas ações aqui

});

When the name of the city HAS NO accent it can usually get the current climate data. But city with accent (for example: Avaí-SP, Arujá-SP) I’m getting an error 500:

   {
"timestamp":1530038926783,
"status":500,
"error":"Internal Server Error",
"exception":"org.json.simple.parser.ParseException",
"message":"No message available",
"path":"/clima/Altin%C3%B3polis/SP/agora"
}

What am I doing wrong that city with accent it is always giving problem?

DETAIL: in LOCALHOST is working perfectly! But when I go up to the server these cities with accent do not work.

  • See if the generated URL is exactly the same on the server and at your location to begin with. When the city is not found, a json comes with an empty array instead of an object, I believe that could be it. Opening the link direct at http://apiadvisor.climatempo.com.br/api/v1/locale/city?name=Altin%C3%B3polis&state=sp&token=xxx, returned an object correctly here for me.

  • On the server the URL is coming (at least in the log too) with these symbols ( %C3%B3 as in the example ).

  • Yes, this is the ó of Antinópolis. But by pasting the URL both with ó and with this code in place, Json returns in the browser. If you notice well in the message, the error occurs on your server when reading the return Json. If it works on one server and not on the other, I think it may be different Urls, or that the other server cannot see the site of the Climatempo... on this server, try to access the manually generated link to test for example.

1 answer

2


I decided to ENCODE the City name that I receive via get BEFORE sending to Endpoint Climatempo. Getting this way:

//Encode the nomeCidade to send to the ClimaTempo Endpoint
//(This must be done because of the accents)

String newNomeCidade = nomeCidade.toLowerCase();
try {
    newNomeCidade = URLEncoder.encode(newNomeCidade, "UTF-8");
} catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
    e1.printStackTrace();
}       
JSONObject climaCidade = new JSONObject();
ClimaTempoAPI ct = new ClimaTempoAPI();

String weatherEndpoint = "/api/v1/locale/city?name=" + newNomeCidade + "&state=" + ufCidade.toString();
climaCidade = ct.RequestWeather(weatherEndpoint, appToken.getKey());

I used "city name.toLowerCase()" because for some reason, if the first letter of the city name had an accent and was capitalized, the Climatempo API endpoint would return an exception, which would only be solved if it was all minuscule.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.