You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java调用Exchange Rates API传全参数仍获403响应码的原因

Java调用Exchange Rates API故障排查与修复

可能的问题点及解决步骤:

  1. 未捕获错误响应详情
    你当前只打印了响应码,但没获取非200状态下API返回的错误信息,这是排查问题的核心。比如API key无效、参数格式错误、接口权限不足等,API都会返回具体的错误提示。需要在else分支里读取错误流:
else {
    System.out.println("GET request failed, response code: " + responseCode);
    // 读取错误响应内容
    BufferedReader errorIn = new BufferedReader(new InputStreamReader(httpURLConnection.getErrorStream()));
    String errorLine;
    StringBuffer errorResponse = new StringBuffer();
    while((errorLine = errorIn.readLine()) != null){
        errorResponse.append(errorLine);
    }
    errorIn.close();
    System.out.println("Error message: " + errorResponse.toString());
}
  1. JSON解析逻辑错误
    根据Exchange Rates API的convert接口返回格式,rates字段下的键是目标货币代码(toCode),而非源货币代码(fromCode)。你现在用fromCode去取值会抛出JSON异常,修正如下:
// 原代码(错误)
Double exchangeRate = obj.getJSONObject("rates").getDouble(fromCode);
// 修改后
Double exchangeRate = obj.getJSONObject("rates").getDouble(toCode);
  1. 参数拼接格式问题
    直接将double类型的amount拼接到URL中,可能因地区本地化格式(比如用逗号代替小数点)导致参数无效。建议用String.format标准化格式:
// 原代码
String GET_URL = "https://api.apilayer.com/exchangerates_data/convert?to="+toCode+"&from="+fromCode+"&amount="+amount;
// 修改后
String GET_URL = String.format("https://api.apilayer.com/exchangerates_data/convert?to=%s&from=%s&amount=%.2f", toCode, fromCode, amount);
  1. API Key有效性验证
    确认你的API Key是否正确、未过期,且拥有exchangerates_data/convert接口的访问权限。可以先通过Postman等工具直接调用接口,验证Key的有效性,排除代码外的问题。

修正后的完整代码示例:

private static void sendHttpGETRequest(String fromCode, String toCode, double amount) throws IOException, JSONException{
        
    String GET_URL = String.format("https://api.apilayer.com/exchangerates_data/convert?to=%s&from=%s&amount=%.2f", toCode, fromCode, 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(toCode);
        System.out.println(obj.getJSONObject("rates"));
        System.out.println(exchangeRate); //keep for debugging
        System.out.println();
        
    } 
    else {
        System.out.println("GET request failed, response code: " + responseCode);
        // 读取错误响应内容
        BufferedReader errorIn = new BufferedReader(new InputStreamReader(httpURLConnection.getErrorStream()));
        String errorLine;
        StringBuffer errorResponse = new StringBuffer();
        while((errorLine = errorIn.readLine()) != null){
            errorResponse.append(errorLine);
        }
        errorIn.close();
        System.out.println("Error message: " + errorResponse.toString());
    }                                           
}

内容的提问来源于stack exchange,提问作者BluesGo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 23:25:18