在线调试
填写业务相关参数免费在线调试
输入任意币种(中文名 / 英文 ISO / slug 三种写法均可),秒级返回该币种在国内 19 家主要银行的最新现汇买卖价、现钞买卖价、中行公布中间价与折算价。配套独家"现汇卖出价"最低 / 最高 / 平均统计字段,可直接驱动"哪家银行换汇最划算"对比视图。10 分钟本地缓存命中毫秒级,覆盖美元 / 欧元 / 日元 / 港币 / 英镑等 30 个常见币种。
全站会员->单独包月->次数包->点数计费->账户余额->免费额度
全站会员有效期内,可免费使用本产品。
| 免费/测试用户请求频率限制 | 请求频率总限制 | 全站会员请求频率限制 | 每日请求次数总限制 |
|---|---|---|---|
| 3秒1次 每个免费用户的QPS总限制 | 1秒1次 每个用户QPS总限制 | 1秒10次 每个全站会员用户的QPS总限制 | 10000 (次) 每个用户每日请求总次数 |
接口地址:https://daoyouapi.com/api/aaa/index
返回格式:application/json
请求方式:HTTPGET
请求示例:https://daoyouapi.com/api/aaa/index?key=你的密钥¤cy=看文档
| 名称 | 值 |
|---|---|
| Content-Type | application/x-www-form-urlencoded;charset:utf-8; |
| 名称 | 必填 | 类型 | 示例值 | 说明 |
|---|---|---|---|---|
| key | 是 | string | 35kj5jnlj53453kl5j43nj5 | 接口密钥,在控制台->密钥管理查看 |
| currency | 是 | string | usd | 币种,支持 slug / ISO 大小写 / 中文名(如:usd、USD、美元),共 30 个币种 |
| 名称 | 类型 | 说明 |
|---|---|---|
| code | int | 状态码,200=成功 |
| success | bool | 是否成功 |
| message | string | 状态信息 |
| data.engine | string | 引擎标识 |
| data.note | string | 价格单位与字段说明 |
| data.currency | object | 查询币种基础信息 |
| data.currency.slug | string | 币种 slug |
| data.currency.name | string | 币种中文名 |
| data.currency.iso | string | 币种 ISO 代码 |
| data.global_updated_at | string | 页面顶部的数据更新时间 |
| data.count | int | 本次返回的银行数 |
| data.list | array | 各银行牌价清单 |
| data.list[].bank_slug | string | 银行 slug |
| data.list[].bank_name | string | 银行中文名 |
| data.list[].bank_tel | string | 银行客服电话 |
| data.list[].cash_buy | float/null | 现汇买入价(银行收购现汇) |
| data.list[].cash_sell | float/null | 现汇卖出价(银行卖出现汇) |
| data.list[].cash_mid | float/null | 现汇中间价 |
| data.list[].note_buy | float/null | 现钞买入价 |
| data.list[].note_sell | float/null | 现钞卖出价 |
| data.list[].note_mid | float/null | 现钞中间价 |
| data.list[].middle_price | float/null | 中行公布中间价 |
| data.list[].conversion_price | float/null | 折算价 |
| data.list[].updated_at | string | 该银行牌价更新时间 |
| data.summary | object/null | 跨行现汇卖出价汇总统计 |
| data.summary.min_cash_sell | float | 现汇卖出价最低值(最划算) |
| data.summary.max_cash_sell | float | 现汇卖出价最高值 |
| data.summary.avg_cash_sell | float | 现汇卖出价平均值 |
| data.summary.note | string | 统计口径说明 |
| debug | string/array | 调试数据 |
| exec_time | float | 执行耗时(秒) |
| user_ip | string | 客户端IP |
| timestamp | int | 服务器时间戳 |
本服务仅供个人学习、学术研究目的使用,未经授权,请勿分享、传播输入及生成的文本、图片内容。用户在从事与本服务相关的一切行为(包括但不限于访问浏览、利用、转载、宣传介绍)时,应以善意且谨慎的态度行事并承担相应的风险和责任。用户需确保不得利用本服务进行危害国家安全和社会公共利益、扰乱经济秩序和社会秩序、侵犯他人合法权益等法律、行政法规禁止的活动,并且自定义输入文本不得包含违反法律法规、政治相关、侵犯他人合法权益的内容。对于用户因使用本服务而导致的任何损失或风险,包括但不限于由于使用本服务而产生的错误、疏忽、中断、删除、故障、延迟或通讯线路故障所导致的任何损失或损害,本服务的开发者将不承担任何责任。
{}
- "code": 200,
- "success": true,
- "message": "查询成功",
-"data": {},
-"currency": {},- "global_updated_at": "2026-05-17 18:55:42",
- "count": 19,
-"list": [],
-{},
- "bank_slug": "boc",
- "bank_name": "中国银行",
- "cash_buy": 6.8046,
- "cash_sell": 6.8333,
- "cash_mid": null,
- "note_buy": 6.8046,
- "note_sell": 6.8333,
- "note_mid": null,
- "middle_price": null,
- "conversion_price": 6.8415,
- "updated_at": "2026-05-17 10:30:00",
- "bank_tel": "95566"
-{},
- "bank_slug": "icbc",
- "bank_name": "中国工商银行",
- "cash_buy": 6.7937,
- "cash_sell": 6.8292,
- "cash_mid": null,
- "note_buy": 6.7937,
- "note_sell": 6.8292,
- "note_mid": null,
- "middle_price": null,
- "conversion_price": null,
- "updated_at": "2026-05-16 03:00:16",
- "bank_tel": "95588"
-{},
- "bank_slug": "ccb",
- "bank_name": "中国建设银行",
- "cash_buy": 6.8073,
- "cash_sell": 6.8366,
- "cash_mid": null,
- "note_buy": 6.8073,
- "note_sell": 6.8366,
- "note_mid": null,
- "middle_price": null,
- "conversion_price": null,
- "updated_at": "2026-05-17 10:55:14",
- "bank_tel": "95533"
-{},
- "bank_slug": "abchina",
- "bank_name": "中国农业银行",
- "cash_buy": 6.79937,
- "cash_sell": 6.82799,
- "cash_mid": null,
- "note_buy": 6.79937,
- "note_sell": null,
- "note_mid": null,
- "middle_price": null,
- "conversion_price": null,
- "updated_at": "2026-05-17 18:55:01",
- "bank_tel": "95599"
-{},
- "bank_slug": "bankcomm",
- "bank_name": "交通银行",
- "cash_buy": 6.8017,
- "cash_sell": 6.8309,
- "cash_mid": null,
- "note_buy": 6.8017,
- "note_sell": 6.8309,
- "note_mid": null,
- "middle_price": null,
- "conversion_price": null,
- "updated_at": "2026-05-17 18:50:00",
- "bank_tel": "95559"
-{},
- "bank_slug": "cmbchina",
- "bank_name": "招商银行",
- "cash_buy": 6.7937,
- "cash_sell": 6.8369,
- "cash_mid": null,
- "note_buy": 6.7937,
- "note_sell": 6.8369,
- "note_mid": null,
- "middle_price": null,
- "conversion_price": null,
- "updated_at": "2026-05-17 18:55:25",
- "bank_tel": "95555"
-{},
- "bank_slug": "psbc",
- "bank_name": "中国邮政储蓄银行",
- "cash_buy": 6.7984,
- "cash_sell": 6.8292,
- "cash_mid": null,
- "note_buy": 6.7984,
- "note_sell": null,
- "note_mid": null,
- "middle_price": null,
- "conversion_price": 6.8292,
- "updated_at": "2026-05-17 05:50:05",
- "bank_tel": "95580"
-{},
- "bank_slug": "hsbc",
- "bank_name": "汇丰银行",
- "cash_buy": 6.7691425,
- "cash_sell": 6.8508636,
- "cash_mid": null,
- "note_buy": 6.7285333,
- "note_sell": 6.8508636,
- "note_mid": null,
- "middle_price": null,
- "conversion_price": null,
- "updated_at": "2026-05-17 18:55:26",
- "bank_tel": "4008208878"
-{},
- "bank_slug": "cib",
- "bank_name": "兴业银行",
- "cash_buy": 6.8027,
- "cash_sell": 6.8286,
- "cash_mid": null,
- "note_buy": 6.7455,
- "note_sell": 6.8272,
- "note_mid": null,
- "middle_price": null,
- "conversion_price": null,
- "updated_at": "2026-05-17 05:30:00",
- "bank_tel": "95561"
-{},
- "bank_slug": "citicbank",
- "bank_name": "中信银行",
- "cash_buy": 6.8,
- "cash_sell": 6.8321,
- "cash_mid": null,
- "note_buy": null,
- "note_sell": null,
- "note_mid": null,
- "middle_price": null,
- "conversion_price": null,
- "updated_at": "2026-05-17 03:00:05",
- "bank_tel": "95558"
-{},
- "bank_slug": "pingan",
- "bank_name": "平安银行",
- "cash_buy": 6.799426,
- "cash_sell": 6.829896,
- "cash_mid": null,
- "note_buy": 6.745124,
- "note_sell": 6.829896,
- "note_mid": null,
- "middle_price": 6.8128,
- "conversion_price": null,
- "updated_at": "2026-05-17 18:55:00",
- "bank_tel": "95511"
-{},
- "bank_slug": "cebbank",
- "bank_name": "中国光大银行",
- "cash_buy": 6.799004,
- "cash_sell": 6.826244,
- "cash_mid": 6.8099,
- "note_buy": null,
- "note_sell": null,
- "note_mid": null,
- "middle_price": null,
- "conversion_price": null,
- "updated_at": "2026-05-16 07:00:01",
- "bank_tel": "95595"
-{},
- "bank_slug": "hxb",
- "bank_name": "华夏银行",
- "cash_buy": 6.7976,
- "cash_sell": 6.8228,
- "cash_mid": 6.8099,
- "note_buy": 6.7976,
- "note_sell": 6.8228,
- "note_mid": null,
- "middle_price": null,
- "conversion_price": null,
- "updated_at": "2026-05-17 18:45:00",
- "bank_tel": "95577"
-{},
- "bank_slug": "cgbchina",
- "bank_name": "广发银行",
- "cash_buy": 6.8018,
- "cash_sell": 6.8263,
- "cash_mid": null,
- "note_buy": 6.8018,
- "note_sell": 6.8263,
- "note_mid": null,
- "middle_price": 6.8127,
- "conversion_price": null,
- "updated_at": "2026-05-17 18:12:25",
- "bank_tel": "95508"
-{},
- "bank_slug": "spdb",
- "bank_name": "浦发银行",
- "cash_buy": 6.7927,
- "cash_sell": 6.8328,
- "cash_mid": null,
- "note_buy": 6.7427,
- "note_sell": 6.8328,
- "note_mid": null,
- "middle_price": 6.8128,
- "conversion_price": null,
- "updated_at": "2026-05-17 18:50:41",
- "bank_tel": "95528"
-{},
- "bank_slug": "cbhb",
- "bank_name": "渤海银行",
- "cash_buy": 6.7963,
- "cash_sell": null,
- "cash_mid": null,
- "note_buy": 6.7418,
- "note_sell": 6.8235,
- "note_mid": null,
- "middle_price": null,
- "conversion_price": null,
- "updated_at": "2026-05-17 18:55:25",
- "bank_tel": "95541"
-{},
- "bank_slug": "czbank",
- "bank_name": "浙商银行",
- "cash_buy": 6.7991,
- "cash_sell": 6.8307,
- "cash_mid": null,
- "note_buy": null,
- "note_sell": 6.8307,
- "note_mid": null,
- "middle_price": null,
- "conversion_price": null,
- "updated_at": "2026-05-17 18:55:25",
- "bank_tel": "95527"
-{},
- "bank_slug": "srcb",
- "bank_name": "上海农村商业银行",
- "cash_buy": 6.797,
- "cash_sell": 6.8285,
- "cash_mid": null,
- "note_buy": 6.797,
- "note_sell": 6.8285,
- "note_mid": null,
- "middle_price": 6.8128,
- "conversion_price": null,
- "updated_at": "2026-05-17 18:50:00",
- "bank_tel": "962999"
-{}
- "bank_slug": "hfbank",
- "bank_name": "恒丰银行",
- "cash_buy": 6.7953,
- "cash_sell": 6.8247,
- "cash_mid": null,
- "note_buy": 6.7373,
- "note_sell": null,
- "note_mid": 6.8095,
- "middle_price": null,
- "conversion_price": null,
- "updated_at": "2026-05-17 18:44:00",
- "bank_tel": "95395"
-"summary": {},
- "min_cash_sell": 6.8228,
- "max_cash_sell": 6.850864,
- "avg_cash_sell": 6.830977,
- "note": "基于"现汇卖出价"统计,即客户用人民币购买外汇时使用的银行报价。"
- "engine": "咔咔云外汇牌价智核 v1.0",
- "note": "价格单位均为人民币(CNY)。1单位外币兑换若干人民币,"-"表示该银行未公开此项报价。"
- "debug": "",
- "exec_time": 0.3839,
- "user_ip": "175.161.45.2",
- "timestamp": 1779083706,
- "tip": "此接口由咔咔云独家开发,购买开源接口源码联系QQ:79087446"
| 错误码 | 类型 | 说明 |
|---|---|---|
| 403 | int | 没有权限 |
| 400 | int | 参数传递不正确 |
| 500 | int | 服务器内部错误 |
<?php
/**
* API请求DEMO
*
* 本demo支持常见的HTTP请求方法(GET/POST/PUT/DELETE等)
*/
//基本配置
$api_key = '你的接口密钥,登录控制台后在密钥管理页面申请';
$secret_key = '';
// API请求示例:
try {
$client = new ApiClient($api_key, $secret_key);
$client->setTimeout(10);
$client->setVerifySSL(false); // 关闭SSL验证
// GET请求示例
echo "=== 开始GET请求 ===\n";
$response = $client->get('https://daoyouapi.com/api/aaa/index', [
'key' => $api_key,
'key2' => '其他参数'
]);
print_r($response);
//print_r($client->getLastRequestInfo());
/*
// POST表单示例
echo "\n=== 开始POST请求 ===\n";
$response = $client->post('接口地址', [
'key' => $api_key,
'key2' => '其他参数'
]);
print_r($response);
print_r($client->getLastRequestInfo());
// POST JSON示例
echo "\n=== 开始POST JSON请求 ===\n";
$response = $client->postJson('接口地址', [
'key' => $api_key,
'key2' => '其他参数'
]);
print_r($response);
print_r($client->getLastRequestInfo());
*/
} catch (ApiClientException $e) {
echo "API请求错误: " . $e->getMessage();
if ($e->getCode() > 0) {
echo " (HTTP状态码: " . $e->getCode() . ")";
}
print_r($client->getLastRequestInfo() ?? []);
}
/**
* API客户端类
*
* 提供了一个简单的HTTP API客户端实现,支持常见的HTTP请求方法(GET/POST/PUT/DELETE等)
* 具有以下主要功能:
* - 支持 API 密钥和签名认证
* - 可配置请求超时和SSL验证
* - 支持自定义请求头
* - 支持表单和JSON格式的请求体
* - 自动解析响应结果
* - 提供详细的请求信息记录
*
* 使用示例:
* ```
* $client = new ApiClient('https://api.example.com', 'api_key', 'secret_key');
* $response = $client->get('/users', ['page' => 1]);
* ```
*
* @throws ApiClientException 当API请求失败时抛出异常
*/
class ApiClient
{
private $apiKey;
private $secretKey;
private $timeout = 30;
private $verifySSL = true;
private $lastRequestInfo = [];
private $defaultHeaders = [];
/**
* 构造函数
*
* @param string $apiKey API密钥(可选)
* @param string $secretKey 签名密钥(可选)
*/
public function __construct(string $apiKey = '', string $secretKey = '')
{
$this->apiKey = $apiKey;
$this->secretKey = $secretKey;
}
/**
* 设置请求超时时间(秒)
*/
public function setTimeout(int $seconds): self
{
$this->timeout = $seconds;
return $this;
}
/**
* 设置是否验证SSL证书
*/
public function setVerifySSL(bool $verify): self
{
$this->verifySSL = $verify;
return $this;
}
/**
* 添加默认请求头
*/
public function addDefaultHeader(string $name, string $value): self
{
$this->defaultHeaders[$name] = $value;
return $this;
}
/**
* 发送GET请求
*
* @param string $endpoint 接口端点
* @param array $query 查询参数
* @param array $headers 额外请求头
*/
public function get(string $endpoint, array $query = [], array $headers = []): array
{
return $this->request('GET', $endpoint, [
'query' => $query,
'headers' => $headers
]);
}
/**
* 发送POST请求(表单格式)
*
* @param string $endpoint 接口端点
* @param array $data POST数据
* @param array $headers 额外请求头
*/
public function post(string $endpoint, array $data = [], array $headers = []): array
{
return $this->request('POST', $endpoint, [
'form_data' => $data,
'headers' => $headers
]);
}
/**
* 发送POST请求(JSON格式)
*
* @param string $endpoint 接口端点
* @param array $data POST数据
* @param array $headers 额外请求头
*/
public function postJson(string $endpoint, array $data = [], array $headers = []): array
{
return $this->request('POST', $endpoint, [
'json' => $data,
'headers' => array_merge(['Content-Type' => 'application/json'], $headers)
]);
}
/**
* 发送PUT请求
*/
public function put(string $endpoint, array $data = [], array $headers = []): array
{
return $this->request('PUT', $endpoint, [
'json' => $data,
'headers' => $headers
]);
}
/**
* 发送DELETE请求
*/
public function delete(string $endpoint, array $data = [], array $headers = []): array
{
return $this->request('DELETE', $endpoint, [
'json' => $data,
'headers' => $headers
]);
}
/**
* 获取最后一次请求的详细信息
*/
public function getLastRequestInfo(): array
{
return $this->lastRequestInfo;
}
/**
* 基础请求方法
*/
private function request(string $method, string $endpoint, array $options = []): array
{
// 初始化cURL
$ch = curl_init();
$url = ltrim($endpoint, '/');
// 准备请求头
$headers = $this->prepareHeaders($options['headers'] ?? []);
// 处理查询参数
if (!empty($options['query'])) {
$url .= '?' . http_build_query($options['query']);
}
// 处理请求体
$postData = null;
if (isset($options['form_data'])) {
$postData = http_build_query($options['form_data']);
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
} elseif (isset($options['json'])) {
$postData = json_encode($options['json']);
$headers[] = 'Content-Type: application/json';
}
// 设置cURL选项
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_TIMEOUT => $this->timeout,
CURLOPT_SSL_VERIFYPEER => $this->verifySSL,
CURLOPT_SSL_VERIFYHOST => $this->verifySSL,
CURLOPT_HEADER => true,
]);
if ($method !== 'GET' && $postData !== null) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
}
// 执行请求
$response = curl_exec($ch);
$error = curl_error($ch);
$info = $this->lastRequestInfo = curl_getinfo($ch);
curl_close($ch);
// 处理错误
if ($error) {
throw new ApiClientException("cURL请求失败: " . $error);
}
// 分离响应头和响应体
$headerSize = $info['header_size'];
$responseHeaders = substr($response, 0, $headerSize);
$responseBody = substr($response, $headerSize);
// 解析响应
$result = json_decode($responseBody, true) ?? $responseBody;
// 检查HTTP状态码
if ($info['http_code'] >= 400) {
$errorMsg = is_array($result) ? ($result['message'] ?? $responseBody) : $responseBody;
throw new ApiClientException("API请求失败: " . $errorMsg, $info['http_code']);
}
return [
'status' => $info['http_code'],
'headers' => $this->parseHeaders($responseHeaders),
'data' => $result
];
}
/**
* 准备请求头(自动添加签名)
*/
private function prepareHeaders(array $headers): array
{
// 合并默认头
$headers = array_merge($this->defaultHeaders, $headers);
// 添加签名头
if ($this->apiKey && $this->secretKey) {
$timestamp = time();
$signString = "key={$this->apiKey}×tamp={$timestamp}";
$signature = hash_hmac('sha256', $signString, $this->secretKey);
$headers['X-Api-Key'] = $this->apiKey;
$headers['X-Api-Timestamp'] = $timestamp;
$headers['X-Api-Sign'] = $signature;
}
// 转换为cURL格式
$curlHeaders = [];
foreach ($headers as $name => $value) {
$curlHeaders[] = "$name: $value";
}
return $curlHeaders;
}
/**
* 解析响应头
*/
private function parseHeaders(string $headers): array
{
$parsed = [];
foreach (explode("\r\n", $headers) as $i => $line) {
if ($i === 0) {
$parsed['HTTP_CODE'] = $line;
} else {
$parts = explode(': ', $line, 2);
if (count($parts) === 2) {
$parsed[$parts[0]] = $parts[1];
}
}
}
return $parsed;
}
}
class ApiClientException extends \Exception
{
// 自定义异常类
}
//jQuery-Ajax
$.ajax({
url: 'https://daoyouapi.com/api/aaa/index',
data: {
//接口参数,一行一个,可按照接口文档-请求参数 的参数填写,或者直接复制开发工具下面的测试代码。
key: '你的接口密钥,登录控制台后在密钥管理页面申请',
参数名: '参数值',
},
type: 'GET', //请求协议(GET或POST),一般默认GET,部分接口需要POST请求,根据实际情况修改为POST即可。
dataType: 'json',
success: function(data) {
console.log(data); //请求成功,输出结果到控制台
},
timeout: 3000, //超时时间
error: function(data) {
console.log('请求失败'); //失败处理
}
});
| 子程序名 | 返回值类型 | 公开 | 备 注 | ||
| __启动窗口_创建完毕 | |||||
| 子程序名 | 返回值类型 | 公开 | 备 注 | ||
| Send_API | |||||
| 变量名 | 类 型 | 静态 | 数组 | 备 注 | ||
| REQU_Data | 文本型 | 提交字符串 | ||||
| return | 文本型 | 返回字符串 | ||||
| API_URL | 文本型 | 接口地址 | ||||
| API_KEY | 文本型 | 接口密钥 | ||||
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Test {
public static void main(String[] args) {
try {
URL url = new URL("https://daoyouapi.com/api/aaa/index?key=你的接口密钥,登录控制台后在密钥管理页面申请");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
// 设置请求方式
connection.setRequestMethod("GET");
connection.connect();
// 获取响应码
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
// 读取到的内容给line变量
System.out.println(line);
}
reader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
// 发起一个GET请求
resp, err := http.Get("https://daoyouapi.com/api/aaa/index?key=你的接口密钥,登录控制台后在密钥管理页面申请")
if err != nil {
fmt.Println("http get error", err)
return
}
// 读取响应结果
result, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("http read error", err)
return
}
// 关闭响应结果
defer resp.Body.Close()
fmt.Println(string(result))
}
```
# 导入requests库
import requests
# 设置url
url = 'https://daoyouapi.com/api/aaa/index?key=你的接口密钥,登录控制台后在密钥管理页面申请'
# 发送post请求
response = requests.post(url, data={'key1': 'value1', 'key2': 'value2'})
# 获取响应内容
result = response.json()
# 打印结果
print(result)
```
// 以下是使用Node.js进行GET和POST请求API接口的示例代码:
const https = require('https');
const querystring = require('querystring');
// 定义请求选项
const options = {
hostname: 'daoyouapi.com',
path: '/api/aaa/index',
method: 'GET'
};
// 发送GET请求
https.get(options, res => {
console.log(`statusCode: ${res.statusCode}`);
res.on('data', d => {
process.stdout.write(d);
});
}).on('error', error => {
console.error(error);
});
// 发送POST请求
const postData = querystring.stringify({
'key1': 'value1',
'key2': 'value2'
});
const postOptions = {
hostname: 'daoyouapi.com',
path: '/api/aaa/index',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};
const postReq = https.request(postOptions, res => {
console.log(`statusCode: ${res.statusCode}`);
res.on('data', d => {
process.stdout.write(d);
});
});
postReq.on('error', error => {
console.error(error);
});
postReq.write(postData);
postReq.end();
/*
这个示例代码使用Node.js内置的`https`模块进行HTTP请求。
首先定义了一个GET请求的选项,然后使用`https.get()`方法发送了GET请求。在响应流上注册回调函数,以便在收到响应数据时将其输出到控制台。在出现错误时,也注册了错误处理程序。
类似地,我们也定义了一个POST请求选项,并使用`https.request()`方法发送它。需要在请求头中包含适当的`Content-Type`和`Content-Length`以确保服务器可以正确解析请求体。请求体由`write()`方法写入,并在请求结束时通过调用`end()`方法通知请求对象已经完成。
注意,此示例默认使用`querystring`模块将数据作为x-www-form-urlencoded格式进行编码。如果需要使用其他格式(如JSON),则需要相应地更改请求头和请求体的编码方式。
另外,为了确保HTTPS请求的安全性,您也可以添加其他选项,例如验证服务器证书、设置代理等。
*/
以下是使用C语言进行GET和POST请求API接口的示例代码:
``` c
#include
#include
#include
#include // 需要安装curl库
// API地址
const char* url = "https://daoyouapi.com/api/aaa/index";
// GET请求
void getRequest(CURL* curl) {
CURLcode res;
// 设置URL
curl_easy_setopt(curl, CURLOPT_URL, url);
// 执行请求
res = curl_easy_perform(curl);
if(res != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
}
}
// POST请求
void postRequest(CURL* curl) {
CURLcode res;
// 设置URL
curl_easy_setopt(curl, CURLOPT_URL, url);
// 设置POST数据
const char* postData = "key=你的接口密钥,登录控制台后在密钥管理页面申请&key1=value1";
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postData);
// 执行请求
res = curl_easy_perform(curl);
if(res != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
}
}
int main() {
CURL* curl;
CURLcode res;
// 初始化curl
curl = curl_easy_init();
if(curl) {
// 设置SSL验证
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);
// GET请求
getRequest(curl);
// POST请求
postRequest(curl);
// 清理curl资源
curl_easy_cleanup(curl);
}
return 0;
}
```
这个示例代码使用了libcurl库进行HTTP请求。
首先,需要设置API地址。然后,基于`CURL`结构体创建curl句柄,并使用`curl_easy_setopt()`函数设置选项。这里设置了SSL验证,以确保请求的安全性。
在GET请求中,只需将URL设置为选项,然后调用`curl_easy_perform()`函数执行请求即可。
在POST请求中,还需要将POST数据作为字符串传递给`CURLOPT_POSTFIELDS`选项。
需要注意的是,为了避免内存泄漏,应该在使用完curl句柄之后调用`curl_easy_cleanup()`函数进行清理。
除了上述示例代码外,libcurl库还提供了更多高级选项,例如处理HTTP头、上传文件等。可以参考文档进行更详细的了解。
以下是一个使用C++请求API接口的示例代码:
```cpp
#include
#include
int main() {
CURL *curl;
CURLcode res;
std::string url = "https://daoyouapi.com/api/aaa/index?key=你的接口密钥,登录控制台后在密钥管理页面申请";
std::string response;
curl = curl_easy_init();
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, [](char *ptr, size_t size, size_t nmemb, void *userdata) -> size_t {
std::string *response = reinterpret_cast(userdata);
response->append(ptr, size * nmemb);
return size * nmemb;
});
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
res = curl_easy_perform(curl);
if (res == CURLE_OK) {
std::cout << "Response: " << response << std::endl;
} else {
std::cerr << "Error: " << curl_easy_strerror(res) << std::endl;
}
curl_easy_cleanup(curl);
}
return 0;
}
```
解释:
1. 引入需要的头文件:``用于输出结果,``用于使用libcurl库。
2. 定义需要请求的API接口的URL和存储响应数据的字符串变量。
3. 初始化一个CURL对象。
4. 设置CURL对象的参数:请求的URL(`CURLOPT_URL`)、是否跟随重定向(`CURLOPT_FOLLOWLOCATION`)、响应数据的写入函数(`CURLOPT_WRITEFUNCTION`)和响应数据的写入位置(`CURLOPT_WRITEDATA`)。
5. 发送HTTP请求并获取响应数据,判断返回状态码是否OK。
6. 清理CURL对象。
运行该程序会发送GET请求到指定的API接口URL,并在程序终止前将响应数据输出到终端。注意,在使用该示例代码之前需要安装libcurl库。
以下是一个使用C#请求API接口的示例代码:
```csharp
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program {
static async Task Main(string[] args) {
HttpClient client = new HttpClient();
string url = "https://daoyouapi.com/api/aaa/index?key=你的接口密钥,登录控制台后在密钥管理页面申请";
HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode) {
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("Response: " + responseBody);
} else {
Console.WriteLine("Error: " + response.StatusCode);
}
}
}
```
解释:
1. 引用需要的命名空间:`System.Net.Http`用于使用HttpClient类,`System.Threading.Tasks`用于异步执行请求操作。
2. 创建一个HttpClient对象。
3. 定义需要请求的API接口的URL。
4. 发送GET请求到指定的API接口URL,并获取响应结果。
5. 判断响应状态是否成功,如果成功则读取响应数据(使用ReadAsStringAsync方法),否则输出错误信息(使用StatusCode属性)。
运行该程序会发送GET请求到指定的API接口URL,并在程序终止前将响应数据输出到终端。注意,在使用该示例代码之前需要安装.NET Framework或.NET Core SDK。
以下是VB请求API接口的示例代码:
```
' 1. 引入Microsoft XML v6.0库
' 2. 创建一个XMLHTTP对象
Dim xhr As XMLHTTP
Set xhr = New XMLHTTP
' 3. 设置请求的URL、方法,以及是否异步等
xhr.Open "GET", "https://daoyouapi.com/api/aaa/index?key=你的接口密钥,登录控制台后在密钥管理页面申请", False
' 4. 发送请求
xhr.send
' 5. 获取响应结果
Dim responseText As String
responseText = xhr.responseText
' 6. 输出响应结果
Debug.Print responseText
' 7. 释放资源
Set xhr = Nothing
```
在这个示例中,我们创建了一个XMLHTTP对象,用于请求API接口。我们先调用`open`方法来设置请求的URL、方法,以及是否异步。然后,我们发送请求,并使用`responseText`属性来获取响应结果。最后,我们将响应结果打印到控制台,完成操作后释放资源,以防止内存泄漏。请注意,以上示例代码为同步请求,如果想使用异步请求,需要设置第三个参数为`True`,并在请求结束时处理`OnReadyStateChange`事件。
| 参数名 | 填写参数值 |
|---|---|
请 登录 后发表评论
填写业务相关参数免费在线调试
生成符合你的开发语言代码,复制即可
调整你后端部分逻辑代码即可上线使用