当我向 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ão Velha”。
如果我向端点发送“/weather/Americana/SP/now”或“/weather/Piracicaba/SP/now”等 URL,端点将毫无问题地获取 JSON 返回。
但是,如果我向端点发送诸如“/weather/Mairiporã/SP/now”或“/weather/Avaí/SP/now”之类的 URL,ClimaTempo API 将返回 null JSON,并且我会收到 NullPointerException。
我认为这是重音的问题,但我不能只发送不带重音的“/weather/Mairipora/SP/now”,因为 ClimaTempo API 要求城市名称必须带有重音,否则它返回一个 null JSON...
我做错了什么?
最佳答案
您需要对字符进行编码和解码。
<小时/>用 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();
关于java - Ajax - API 端点 - 这是正确的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51082790/