Ajax-API端点-这是正确的方法吗?

时间:2018-06-28 12:20:52

标签: java jquery ajax spring

我向API端点发送AJAX请求时遇到编码问题。

在下面的代码中,我使用Java Spring拥有这个端点:

@Autowired
    ApiKeyRepository apiKeyRepository;  

    @RequestMapping(value= "/weather/{cityName}/{fuCity}/now",  method = {RequestMethod.GET}, produces="application/json" )
        public ResponseEntity<Weather> getWeatherNowByCityName(@PathVariable(value = "cityName") String cityName,  @PathVariable(value = "fuCity") State fuCity) throws JSONException, ParseException, java.text.ParseException {

        String newCityName = cityName.toLowerCase();

            try {

                newCityName = URLDecoder.decode(newCityName , "UTF-8").replace(" ", "%20");         

            } catch (UnsupportedEncodingException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

        String weatherEndpoint = "/api/v1/locale/city?name=" + newCityName + "&state=" + fuCity.toString();

        String appToken = apiKeyRepository.getByservice("climaTempo");

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

        /// From here I send a JSON Request to the 'weatherDomain' to get the Weather from the city and her state that I get from the EndPoint Parameters
    }

然后我将此jQuery Ajax请求发送到端点:

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

$.ajax({
       url: host + '/weather/' + city + '/' + uf + '/now',
       type: 'GET',
       contentType: "application/x-www-form-urlencoded; charset=utf-8",
       async: true
 }).done(function (JSONReturn) {
       //Actions with JSONReturn
 });

但是在巴西,我们有一些带有重音符号和小调的城市,例如“ SP”中的“Avaí”,“ SP”中的“Mairiporã”和“ CE”中的“MissãoVelha”。

如果我向端点发送URL,例如“ / weather / Americana / SP / now”或“ / weather / Piracicaba / SP / now”,则端点将返回JSON,而不会出现问题。

但是,如果我向端点发送“ / weather /Mairiporã/ SP / now”或“ / weather /Avaí/ SP / now”之类的URL,则ClimaTempo API将返回空JSON并得到NullPointerException。

我认为这是重音符号的问题,但是我不能在没有重音符号的情况下仅发送“ / weather / Mairipora / SP / now”,因为ClimaTempo API要求城市名称必须带有重音符号,否则返回空JSON ...

我在做什么错了?

1 个答案:

答案 0 :(得分:1)

您需要对字符进行编码和解码。


使用JavaScript编码

去代替url: host + '/weather/' + city + '/' + uf + '/now',去

url: host + '/weather/' + encodeURIComponent(city) + '/' + uf + '/now'

用Java解码

去代替String newCityName = cityName.toLowerCase();,去

String newCityName = URLDecoder.decode(cityName, Charsets.UTF_8.name()).toLowerCase();