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

API Layer汇率接口HTTP 403错误修复请求

问题排查与修复方案

核心问题分析

  1. API Key传递方式错误:API Layer的exchangerates_data接口要求将API Key通过apikey请求头传递,而非拼接在URL参数中,当前写法不符合接口规范,导致接口无法识别API Key,返回403。
  2. 请求URL参数冗余且错误:
    • 重复传递base参数(URL开头已指定base=USD,后续又追加&base="+base")
    • 添加了大量不属于请求参数的字段(success、timestamp、date、GBP/JPY/EUR等都是接口返回字段,并非请求时需要传入的参数)
  3. JSON解析逻辑错误:接口返回的JSON结构中不存在response字段,当前解析逻辑会直接抛出异常。

修复后的excJSON.java代码

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class excJSON {
    final static String apiKey = "tUxsDwwjT72GgMLoJRprXlqc34wmOzX4";

    public exc getexc(String base, String symbols) {
        // 简化请求URL,仅保留必要参数
        String urlStr = String.format("https://api.apilayer.com/exchangerates_data/latest?base=%s&symbols=%s", base, symbols);
        
        exc vl = new exc();
        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 通过请求头传递API Key,符合接口规范
            conn.setRequestProperty("apikey", apiKey);
            conn.setRequestMethod("GET");

            BufferedReader bf = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = "";
            StringBuilder result = new StringBuilder();
            
            while ((line = bf.readLine()) != null) {
                result.append(line);
            }
            bf.close();
            conn.disconnect();

            // 解析接口返回的正确JSON结构
            JSONParser jsonParser = new JSONParser();
            JSONObject jsonObj = (JSONObject) jsonParser.parse(result.toString());
            
            vl.settimestamp(jsonObj.get("timestamp").toString());
            vl.setbase(jsonObj.get("base").toString());
            vl.setdate(jsonObj.get("date").toString());

        } catch (IOException e) {
            System.out.println("IOException : " + e.getMessage());
        } catch (ParseException e) {
            System.out.println("ParseException : " + e.getMessage());       
        }
        
        return vl;
    }
}

配套的control.java调用修正

public class control {
    public static void main(String[] args) {
        excJSON vwJson = new excJSON();
        // 传入基础货币和目标货币符号
        exc vw = vwJson.getexc("USD", "GBP,JPY,EUR");

        excDAO vwDao = new excDAO();
        vwDao.intertexc(1, vw);
    }
}

额外注意事项

  • 确认API Key处于激活状态,未超出调用额度
  • excDAO.java中的intertexc方法为空实现,需补充调用intertVillageWeather的逻辑,否则数据无法写入数据库

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 13:54:36