我目前正在学习使用Java中的API,我正在使用汇率API,但是,它无法理解发生了什么,我发送了所有请求的参数,我还发送了我的API密钥作为头部。
private static void sendHttpGETRequest(String fromCode, String toCode, double amount) throws IOException, JSONException{
String GET_URL = "https://api.apilayer.com/exchangerates_data/convert?to="+toCode+"&from="+fromCode+"&amount="+amount;
URL url = new URL(GET_URL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(200 * 1000);
httpURLConnection.setConnectTimeout(200 * 1000);
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setRequestProperty("apikey", "MyApiKeY");
int responseCode = httpURLConnection.getResponseCode();
System.out.println("Response code: " + responseCode);
if(responseCode == httpURLConnection.HTTP_OK){//SUCESS
BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while((inputLine = in.readLine()) != null){
response.append(inputLine);
}in.close();
JSONObject obj = new JSONObject(response.toString());
Double exchangeRate = obj.getJSONObject("rates").getDouble(fromCode);
System.out.println(obj.getJSONObject("rates"));
System.out.println(exchangeRate); //keep for debugging
System.out.println();
}
else {
System.out.println("GET request failed");
}
}
我已经使用setConnectTimeout和setReadTimeout来设置网络超时,认为这是问题所在,但仍然得到相同的错误。
1条答案
按热度按时间e3bfsja21#
403
响应代码表示请求有效,但服务器拒绝执行请求。请参见https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/403这可能是由于多种原因造成的,例如用户没有访问API所需的权限,或者API配置不正确,或者只是令牌过期。也可能是API对请求进行了速率限制,用户已超过允许的请求数。
因此,不要只看返回的HTTP状态码,还要看响应正文,通常服务器会给出一些解释。