本文将展示StockAPI对接 Python、Java、PHP、C++、C#、C、NodeJs 请求示例

API 示例接口信息

  • 示例接口地址: https://stockapi.com.cn/v1/base/day
  • 请求方式: GET
  • 返回格式: JSON

请求参数

参数名类型必填说明
tokenstringAPI访问令牌
codestring股票代码(如:600004)
startDatestring开始日期(格式:YYYY-MM-DD)
endDatestring结束日期(格式:YYYY-MM-DD)
calculationCycleint计算周期

完整请求URL示例


https://stockapi.com.cn/v1/base/day?token=你的token&code=600004&endDate=2021-10-15&startDate=2021-10-10&calculationCycle=100
      

Python 示例代码

方法一:使用 requests 库


import requests
import json

# API 配置
base_url = "https://stockapi.com.cn/v1/base/day"
token = "你的token"  # 请替换为实际的token

# 请求参数
params = {
    "token": token,
    "code": "600004",
    "startDate": "2021-10-10",
    "endDate": "2021-10-15",
    "calculationCycle": 100
}

try:
    # 发送GET请求
    response = requests.get(base_url, params=params)
    
    # 检查响应状态
    if response.status_code == 200:
        data = response.json()
        print("请求成功!")
        print(json.dumps(data, indent=2, ensure_ascii=False))
    else:
        print(f"请求失败,状态码:{response.status_code}")
        print(f"响应内容:{response.text}")
        
except requests.exceptions.RequestException as e:
    print(f"请求异常:{e}")
      

方法二:使用 urllib 库(Python 标准库)


import urllib.request
import urllib.parse
import json

# API 配置
base_url = "https://stockapi.com.cn/v1/base/day"
token = "你的token"  # 请替换为实际的token

# 请求参数
params = {
    "token": token,
    "code": "600004",
    "startDate": "2021-10-10",
    "endDate": "2021-10-15",
    "calculationCycle": 100
}

# 构建完整的URL
query_string = urllib.parse.urlencode(params)
full_url = f"{base_url}?{query_string}"

try:
    # 发送GET请求
    with urllib.request.urlopen(full_url) as response:
        data = json.loads(response.read().decode('utf-8'))
        print("请求成功!")
        print(json.dumps(data, indent=2, ensure_ascii=False))
        
except urllib.error.HTTPError as e:
    print(f"HTTP错误:{e.code} - {e.reason}")
except urllib.error.URLError as e:
    print(f"URL错误:{e.reason}")
except Exception as e:
    print(f"其他错误:{e}")
      

Java 示例代码

方法一:使用 HttpURLConnection(Java 标准库)


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class StockApiDemo {
    private static final String BASE_URL = "https://stockapi.com.cn/v1/base/day";
    private static final String TOKEN = "你的token"; // 请替换为实际的token
    
    public static void main(String[] args) {
        try {
            // 构建请求参数
            String params = "token=" + URLEncoder.encode(TOKEN, StandardCharsets.UTF_8) +
                           "&code=" + URLEncoder.encode("600004", StandardCharsets.UTF_8) +
                           "&startDate=" + URLEncoder.encode("2021-10-10", StandardCharsets.UTF_8) +
                           "&endDate=" + URLEncoder.encode("2021-10-15", StandardCharsets.UTF_8) +
                           "&calculationCycle=" + URLEncoder.encode("100", StandardCharsets.UTF_8);
            
            // 创建URL对象
            URL url = new URL(BASE_URL + "?" + params);
            
            // 创建HTTP连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("User-Agent", "Java-StockAPI-Client/1.0");
            
            // 获取响应码
            int responseCode = connection.getResponseCode();
            
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 读取响应内容
                BufferedReader reader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
                StringBuilder response = new StringBuilder();
                String line;
                
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                
                System.out.println("请求成功!");
                System.out.println("响应内容:" + response.toString());
            } else {
                System.out.println("请求失败,状态码:" + responseCode);
                
                // 读取错误响应
                BufferedReader errorReader = new BufferedReader(
                    new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8));
                StringBuilder errorResponse = new StringBuilder();
                String errorLine;
                
                while ((errorLine = errorReader.readLine()) != null) {
                    errorResponse.append(errorLine);
                }
                errorReader.close();
                
                System.out.println("错误内容:" + errorResponse.toString());
            }
            
            connection.disconnect();
            
        } catch (IOException e) {
            System.err.println("请求异常:" + e.getMessage());
            e.printStackTrace();
        }
    }
}
      

方法二:使用 OkHttp 库(推荐)


import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.HttpUrl;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class StockApiOkHttpDemo {
    private static final String BASE_URL = "https://stockapi.com.cn/v1/base/day";
    private static final String TOKEN = "你的token"; // 请替换为实际的token
    
    public static void main(String[] args) {
        // 创建OkHttp客户端
        OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(30, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .build();
        
        try {
            // 构建URL和参数
            HttpUrl.Builder urlBuilder = HttpUrl.parse(BASE_URL).newBuilder();
            urlBuilder.addQueryParameter("token", TOKEN);
            urlBuilder.addQueryParameter("code", "600004");
            urlBuilder.addQueryParameter("startDate", "2021-10-10");
            urlBuilder.addQueryParameter("endDate", "2021-10-15");
            urlBuilder.addQueryParameter("calculationCycle", "100");
            
            String url = urlBuilder.build().toString();
            
            // 创建请求
            Request request = new Request.Builder()
                .url(url)
                .addHeader("Accept", "application/json")
                .addHeader("User-Agent", "Java-OkHttp-StockAPI-Client/1.0")
                .build();
            
            // 执行请求
            try (Response response = client.newCall(request).execute()) {
                if (response.isSuccessful()) {
                    String responseBody = response.body().string();
                    System.out.println("请求成功!");
                    System.out.println("响应内容:" + responseBody);
                } else {
                    System.out.println("请求失败,状态码:" + response.code());
                    System.out.println("错误内容:" + response.body().string());
                }
            }
            
        } catch (IOException e) {
            System.err.println("请求异常:" + e.getMessage());
            e.printStackTrace();
        } finally {
            // 关闭客户端连接池
            client.dispatcher().executorService().shutdown();
            client.connectionPool().evictAll();
        }
    }
}
      

Maven 依赖配置

如果使用 OkHttp 库,需要在 pom.xml 中添加以下依赖:


<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.12.0</version>
</dependency>
      

Gradle 依赖配置

如果使用 Gradle,在 build.gradle 中添加:


implementation 'com.squareup.okhttp3:okhttp:4.12.0'
      

PHP 示例代码

方法一:使用 cURL


<?php
// API 配置
$baseUrl = "https://stockapi.com.cn/v1/base/day";
$token = "你的token"; // 请替换为实际的token

// 请求参数
$params = [
    'token' => $token,
    'code' => '600004',
    'startDate' => '2021-10-10',
    'endDate' => '2021-10-15',
    'calculationCycle' => 100
];

// 构建完整URL
$url = $baseUrl . '?' . http_build_query($params);

// 初始化cURL
$ch = curl_init();

// 设置cURL选项
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-StockAPI-Client/1.0');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Accept: application/json',
    'Content-Type: application/json'
]);

// 执行请求
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);

// 关闭cURL
curl_close($ch);

// 处理响应
if ($error) {
    echo "请求错误: " . $error . "\n";
} elseif ($httpCode === 200) {
    echo "请求成功!\n";
    $data = json_decode($response, true);
    echo "响应内容: " . json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n";
} else {
    echo "请求失败,状态码: " . $httpCode . "\n";
    echo "响应内容: " . $response . "\n";
}
?>
      

方法二:使用 file_get_contents


<?php
// API 配置
$baseUrl = "https://stockapi.com.cn/v1/base/day";
$token = "你的token"; // 请替换为实际的token

// 请求参数
$params = [
    'token' => $token,
    'code' => '600004',
    'startDate' => '2021-10-10',
    'endDate' => '2021-10-15',
    'calculationCycle' => 100
];

// 构建完整URL
$url = $baseUrl . '?' . http_build_query($params);

// 创建上下文
$context = stream_context_create([
    'http' => [
        'method' => 'GET',
        'header' => [
            'Accept: application/json',
            'User-Agent: PHP-StockAPI-Client/1.0'
        ],
        'timeout' => 30
    ]
]);

// 发送请求
$response = @file_get_contents($url, false, $context);

if ($response === false) {
    echo "请求失败\n";
    $error = error_get_last();
    echo "错误信息: " . $error['message'] . "\n";
} else {
    echo "请求成功!\n";
    $data = json_decode($response, true);
    echo "响应内容: " . json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n";
}
?>
      

方法三:使用 Guzzle HTTP 库


<?php
require_once 'vendor/autoload.php';

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

// API 配置
$baseUrl = "https://stockapi.com.cn/v1/base/day";
$token = "你的token"; // 请替换为实际的token

// 请求参数
$params = [
    'token' => $token,
    'code' => '600004',
    'startDate' => '2021-10-10',
    'endDate' => '2021-10-15',
    'calculationCycle' => 100
];

// 创建HTTP客户端
$client = new Client([
    'timeout' => 30,
    'headers' => [
        'Accept' => 'application/json',
        'User-Agent' => 'PHP-Guzzle-StockAPI-Client/1.0'
    ]
]);

try {
    // 发送GET请求
    $response = $client->get($baseUrl, [
        'query' => $params
    ]);
    
    if ($response->getStatusCode() === 200) {
        echo "请求成功!\n";
        $body = $response->getBody()->getContents();
        $data = json_decode($body, true);
        echo "响应内容: " . json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n";
    } else {
        echo "请求失败,状态码: " . $response->getStatusCode() . "\n";
        echo "响应内容: " . $response->getBody()->getContents() . "\n";
    }
    
} catch (RequestException $e) {
    echo "请求异常: " . $e->getMessage() . "\n";
    if ($e->hasResponse()) {
        echo "错误响应: " . $e->getResponse()->getBody()->getContents() . "\n";
    }
} catch (Exception $e) {
    echo "其他异常: " . $e->getMessage() . "\n";
}
?>
      

Composer 依赖安装

如果使用 Guzzle HTTP 库,需要通过 Composer 安装:


composer require guzzlehttp/guzzle
      

或者在 composer.json 中添加依赖:


{
    "require": {
        "guzzlehttp/guzzle": "^7.0"
    }
}
      

C++ 示例代码

使用 libcurl 库


#include <iostream>
 #include <string>
 #include <curl/curl.h>
 #include <json/json.h>

// 回调函数用于接收响应数据
size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* response) {
    size_t totalSize = size * nmemb;
    response->append((char*)contents, totalSize);
    return totalSize;
}

int main() {
    // API 配置
    const std::string baseUrl = "https://stockapi.com.cn/v1/base/day";
    const std::string token = "你的token"; // 请替换为实际的token
    
    // 构建完整URL
    std::string url = baseUrl + "?token=" + token + 
                     "&code=600004&startDate=2021-10-10&endDate=2021-10-15&calculationCycle=100";
    
    // 初始化libcurl
    curl_global_init(CURL_GLOBAL_DEFAULT);
    CURL* curl = curl_easy_init();
    
    if (curl) {
        std::string response;
        
        // 设置URL
        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
        
        // 设置回调函数
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
        
        // 设置超时
        curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30L);
        
        // 设置User-Agent
        curl_easy_setopt(curl, CURLOPT_USERAGENT, "CPP-StockAPI-Client/1.0");
        
        // 设置请求头
        struct curl_slist* headers = nullptr;
        headers = curl_slist_append(headers, "Accept: application/json");
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
        
        // 执行请求
        CURLcode res = curl_easy_perform(curl);
        
        if (res != CURLE_OK) {
             std::cerr << "请求失败: " << curl_easy_strerror(res) << std::endl;
        } else {
            long httpCode;
            curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpCode);
            
            if (httpCode == 200) {
                std::cout << "请求成功!" << std::endl;
                 std::cout << "响应内容: " << response << std::endl;
                
                // 解析JSON(需要jsoncpp库)
                Json::Value jsonData;
                Json::Reader reader;
                if (reader.parse(response, jsonData)) {
                    std::cout << "JSON解析成功" << std::endl;
                     // 可以进一步处理JSON数据
                     if (jsonData.isMember("data") && jsonData["data"].isArray()) {
                         std::cout << "数据条数: " << jsonData["data"].size() << std::endl;
                    }
                } else {
                    std::cout << "JSON解析失败" << std::endl;
                }
            } else {
                std::cout << "请求失败,状态码: " << httpCode << std::endl;
                 std::cout << "响应内容: " << response << std::endl;
            }
        }
        
        // 清理
        curl_slist_free_all(headers);
        curl_easy_cleanup(curl);
    } else {
        std::cerr << "初始化curl失败" << std::endl;
    }
    
    curl_global_cleanup();
    return 0;
}
      

使用 cpprestsdk 库(现代C++异步方式)


#include <iostream>
 #include <string>
 #include <cpprest/http_client.h>
 #include <cpprest/filestream.h>
 #include <cpprest/uri.h>
 #include <cpprest/json.h>

using namespace web;
using namespace web::http;
using namespace web::http::client;
using namespace concurrency::streams;

int main() {
    // API 配置
    const std::string baseUrl = "https://stockapi.com.cn/v1/base/day";
    const std::string token = "你的token"; // 请替换为实际的token
    
    try {
        // 构建URI
        uri_builder builder(utility::conversions::to_string_t(baseUrl));
        builder.append_query(U("token"), utility::conversions::to_string_t(token));
        builder.append_query(U("code"), U("600004"));
        builder.append_query(U("startDate"), U("2021-10-10"));
        builder.append_query(U("endDate"), U("2021-10-15"));
        builder.append_query(U("calculationCycle"), U("100"));
        
        // 创建HTTP客户端
        http_client client(builder.to_uri());
        
        // 创建请求
        http_request request(methods::GET);
        request.headers().add(U("Accept"), U("application/json"));
        request.headers().add(U("User-Agent"), U("CPP-RestSDK-StockAPI-Client/1.0"));
        
        // 发送请求并等待响应
        client.request(request)
        .then([](http_response response) {
             std::wcout << L"状态码: " << response.status_code() << std::endl;
            
            if (response.status_code() == status_codes::OK) {
                return response.extract_json();
            } else {
                std::wcout << L"请求失败,状态码: " << response.status_code() << std::endl;
                return pplx::task_from_result(json::value());
            }
        })
        .then([](json::value jsonResponse) {
            if (!jsonResponse.is_null()) {
                std::wcout << L"请求成功!" << std::endl;
                 std::wcout << L"响应内容: " << jsonResponse.serialize() << std::endl;
                
                // 处理JSON数据
                if (jsonResponse.has_field(U("data")) && jsonResponse[U("data")].is_array()) {
                    auto dataArray = jsonResponse[U("data")].as_array();
                    std::wcout << L"数据条数: " << dataArray.size() << std::endl;
                }
            }
        })
        .wait();
        
    } catch (const std::exception& e) {
        std::cerr << "异常: " << e.what() << std::endl;
    }
    
    return 0;
}
      

编译说明

使用 libcurl 和 jsoncpp


# Ubuntu/Debian
sudo apt-get update
sudo apt-get install libcurl4-openssl-dev libjsoncpp-dev

# 编译
g++ -std=c++11 -o stock_api main.cpp -lcurl -ljsoncpp

# CentOS/RHEL
sudo yum install libcurl-devel jsoncpp-devel
# 或者使用 dnf (较新版本)
sudo dnf install libcurl-devel jsoncpp-devel

# 编译
g++ -std=c++11 -o stock_api main.cpp -lcurl -ljsoncpp
      

使用 cpprestsdk


# Ubuntu/Debian
sudo apt-get install libcpprest-dev

# 编译
g++ -std=c++11 -o stock_api_rest main.cpp -lcpprest -lssl -lcrypto

# CentOS/RHEL
sudo yum install cpprest-devel
# 或者
sudo dnf install cpprest-devel

# 编译
g++ -std=c++11 -o stock_api_rest main.cpp -lcpprest -lssl -lcrypto
      

CMakeLists.txt 示例


cmake_minimum_required(VERSION 3.10)
project(StockAPIDemo)

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

# 查找依赖库
find_package(PkgConfig REQUIRED)
find_package(OpenSSL REQUIRED)

# libcurl 版本
pkg_check_modules(CURL REQUIRED libcurl)
pkg_check_modules(JSONCPP REQUIRED jsoncpp)

add_executable(stock_api_curl main_curl.cpp)
target_link_libraries(stock_api_curl ${CURL_LIBRARIES} ${JSONCPP_LIBRARIES})
target_include_directories(stock_api_curl PRIVATE ${CURL_INCLUDE_DIRS} ${JSONCPP_INCLUDE_DIRS})

# cpprestsdk 版本
find_package(cpprestsdk REQUIRED)
add_executable(stock_api_rest main_rest.cpp)
target_link_libraries(stock_api_rest cpprestsdk::cpprest OpenSSL::SSL OpenSSL::Crypto)
      

C# 示例代码

使用 HttpClient(推荐)


using System;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace StockApiDemo
{
    class Program
    {
        private static readonly HttpClient client = new HttpClient();
        
        static async Task Main(string[] args)
        {
            // API 配置
            string baseUrl = "https://stockapi.com.cn/v1/base/day";
            string token = "你的token"; // 请替换为实际的token
            
            // 构建请求URL
            string requestUrl = $"{baseUrl}?token={token}&code=600004&startDate=2021-10-10&endDate=2021-10-15&calculationCycle=100";
            
            try
            {
                // 设置请求头
                client.DefaultRequestHeaders.Clear();
                client.DefaultRequestHeaders.Add("User-Agent", "CSharp-StockAPI-Client/1.0");
                client.DefaultRequestHeaders.Add("Accept", "application/json");
                
                // 设置超时时间
                client.Timeout = TimeSpan.FromSeconds(30);
                
                Console.WriteLine("正在发送请求...");
                Console.WriteLine($"请求URL: {requestUrl}");
                
                // 发送GET请求
                HttpResponseMessage response = await client.GetAsync(requestUrl);
                
                // 检查响应状态
                if (response.IsSuccessStatusCode)
                {
                    // 读取响应内容
                    string responseContent = await response.Content.ReadAsStringAsync();
                    
                    Console.WriteLine("请求成功!");
                    Console.WriteLine($"状态码: {response.StatusCode}");
                    Console.WriteLine($"响应内容: {responseContent}");
                    
                    // 解析JSON
                    try
                    {
                        JObject jsonResponse = JObject.Parse(responseContent);
                        
                        Console.WriteLine("JSON解析成功");
                        
                        // 检查是否有data字段
                        if (jsonResponse["data"] != null && jsonResponse["data"] is JArray dataArray)
                        {
                            Console.WriteLine($"数据条数: {dataArray.Count}");
                            
                            // 遍历前几条数据
                            int displayCount = Math.Min(3, dataArray.Count);
                            for (int i = 0; i < displayCount; i++)
                            {
                                var item = dataArray[i];
                                Console.WriteLine($"第{i + 1}条数据: {item}");
                            }
                        }
                        
                        // 检查错误信息
                        if (jsonResponse["error"] != null)
                        {
                            Console.WriteLine($"API错误: {jsonResponse["error"]}");
                        }
                    }
                    catch (JsonException ex)
                    {
                        Console.WriteLine($"JSON解析失败: {ex.Message}");
                    }
                }
                else
                {
                    string errorContent = await response.Content.ReadAsStringAsync();
                    Console.WriteLine($"请求失败,状态码: {response.StatusCode}");
                    Console.WriteLine($"错误内容: {errorContent}");
                }
            }
            catch (HttpRequestException ex)
            {
                Console.WriteLine($"网络请求异常: {ex.Message}");
            }
            catch (TaskCanceledException ex)
            {
                Console.WriteLine($"请求超时: {ex.Message}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"发生异常: {ex.Message}");
            }
        }
    }
}
      

使用 WebRequest(传统方式)


using System;
using System.IO;
using System.Net;
using Newtonsoft.Json.Linq;

namespace StockApiDemo
{
    class WebRequestExample
    {
        static void Main(string[] args)
        {
            // API 配置
            string baseUrl = "https://stockapi.com.cn/v1/base/day";
            string token = "你的token"; // 请替换为实际的token
            
            // 构建请求URL
            string requestUrl = $"{baseUrl}?token={token}&code=600004&startDate=2021-10-10&endDate=2021-10-15&calculationCycle=100";
            
            try
            {
                // 创建WebRequest
                WebRequest request = WebRequest.Create(requestUrl);
                request.Method = "GET";
                request.ContentType = "application/json";
                request.Timeout = 30000; // 30秒超时
                
                // 设置请求头
                if (request is HttpWebRequest httpRequest)
                {
                    httpRequest.UserAgent = "CSharp-WebRequest-StockAPI-Client/1.0";
                    httpRequest.Accept = "application/json";
                }
                
                Console.WriteLine("正在发送请求...");
                Console.WriteLine($"请求URL: {requestUrl}");
                
                // 获取响应
                using (WebResponse response = request.GetResponse())
                {
                    Console.WriteLine($"状态码: {((HttpWebResponse)response).StatusCode}");
                    
                    // 读取响应流
                    using (Stream responseStream = response.GetResponseStream())
                    using (StreamReader reader = new StreamReader(responseStream))
                    {
                        string responseContent = reader.ReadToEnd();
                        
                        Console.WriteLine("请求成功!");
                        Console.WriteLine($"响应内容: {responseContent}");
                        
                        // 解析JSON
                        try
                        {
                            JObject jsonResponse = JObject.Parse(responseContent);
                            Console.WriteLine("JSON解析成功");
                            
                            if (jsonResponse["data"] != null && jsonResponse["data"] is JArray dataArray)
                            {
                                Console.WriteLine($"数据条数: {dataArray.Count}");
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"JSON解析失败: {ex.Message}");
                        }
                    }
                }
            }
            catch (WebException ex)
            {
                Console.WriteLine($"网络异常: {ex.Message}");
                
                if (ex.Response != null)
                {
                    using (Stream errorStream = ex.Response.GetResponseStream())
                    using (StreamReader reader = new StreamReader(errorStream))
                    {
                        string errorContent = reader.ReadToEnd();
                        Console.WriteLine($"错误响应: {errorContent}");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"发生异常: {ex.Message}");
            }
        }
    }
}
      

使用 RestSharp 库(第三方库)


using System;
using RestSharp;
using Newtonsoft.Json.Linq;

namespace StockApiDemo
{
    class RestSharpExample
    {
        static void Main(string[] args)
        {
            // API 配置
            string baseUrl = "https://stockapi.com.cn";
            string token = "你的token"; // 请替换为实际的token
            
            // 创建RestClient
            var client = new RestClient(baseUrl);
            
            // 创建请求
            var request = new RestRequest("/v1/base/day", Method.Get);
            
            // 添加查询参数
            request.AddParameter("token", token);
            request.AddParameter("code", "600004");
            request.AddParameter("startDate", "2021-10-10");
            request.AddParameter("endDate", "2021-10-15");
            request.AddParameter("calculationCycle", "100");
            
            // 设置请求头
            request.AddHeader("Accept", "application/json");
            request.AddHeader("User-Agent", "CSharp-RestSharp-StockAPI-Client/1.0");
            
            // 设置超时
            request.Timeout = 30000;
            
            try
            {
                Console.WriteLine("正在发送请求...");
                
                // 执行请求
                var response = client.Execute(request);
                
                if (response.IsSuccessful)
                {
                    Console.WriteLine("请求成功!");
                    Console.WriteLine($"状态码: {response.StatusCode}");
                    Console.WriteLine($"响应内容: {response.Content}");
                    
                    // 解析JSON
                    try
                    {
                        JObject jsonResponse = JObject.Parse(response.Content);
                        Console.WriteLine("JSON解析成功");
                        
                        if (jsonResponse["data"] != null && jsonResponse["data"] is JArray dataArray)
                        {
                            Console.WriteLine($"数据条数: {dataArray.Count}");
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"JSON解析失败: {ex.Message}");
                    }
                }
                else
                {
                    Console.WriteLine($"请求失败,状态码: {response.StatusCode}");
                    Console.WriteLine($"错误信息: {response.ErrorMessage}");
                    Console.WriteLine($"响应内容: {response.Content}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"发生异常: {ex.Message}");
            }
        }
    }
}
      

NuGet 包依赖

基础依赖(JSON处理)


<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
      

RestSharp 依赖


<PackageReference Include="RestSharp" Version="110.2.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
      

通过 Package Manager Console 安装


# 安装 Newtonsoft.Json
Install-Package Newtonsoft.Json

# 安装 RestSharp
Install-Package RestSharp
      

通过 .NET CLI 安装


# 安装 Newtonsoft.Json
dotnet add package Newtonsoft.Json

# 安装 RestSharp
dotnet add package RestSharp
      

项目文件示例(.csproj)


<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
    <PackageReference Include="RestSharp" Version="110.2.0" />
  </ItemGroup>

</Project>
      

C 示例代码

使用 libcurl 库


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include <json-c/json.h>

// 用于存储响应数据的结构体
struct APIResponse {
    char *data;
    size_t size;
};

// 回调函数,用于接收HTTP响应数据
size_t WriteCallback(void *contents, size_t size, size_t nmemb, struct APIResponse *response) {
    size_t realsize = size * nmemb;
    char *ptr = realloc(response->data, response->size + realsize + 1);
    
    if (ptr == NULL) {
        printf("内存分配失败\n");
        return 0;
    }
    
    response->data = ptr;
    memcpy(&(response->data[response->size]), contents, realsize);
    response->size += realsize;
    response->data[response->size] = 0; // 添加字符串结束符
    
    return realsize;
}

int main() {
    CURL *curl;
    CURLcode res;
    struct APIResponse response = {0};
    
    // API 配置
    const char *base_url = "https://stockapi.com.cn/v1/base/day";
    const char *token = "你的token"; // 请替换为实际的token
    
    // 构建完整的URL
    char url[1024];
    snprintf(url, sizeof(url), 
        "%s?token=%s&code=600004&startDate=2021-10-10&endDate=2021-10-15&calculationCycle=100",
        base_url, token);
    
    printf("正在发送请求...\n");
    printf("请求URL: %s\n", url);
    
    // 初始化libcurl
    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();
    
    if (curl) {
        // 设置URL
        curl_easy_setopt(curl, CURLOPT_URL, url);
        
        // 设置回调函数
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
        
        // 设置超时时间
        curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30L);
        
        // 设置User-Agent
        curl_easy_setopt(curl, CURLOPT_USERAGENT, "C-StockAPI-Client/1.0");
        
        // 设置请求头
        struct curl_slist *headers = NULL;
        headers = curl_slist_append(headers, "Accept: application/json");
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
        
        // 执行请求
        res = curl_easy_perform(curl);
        
        if (res != CURLE_OK) {
            printf("请求失败: %s\n", curl_easy_strerror(res));
        } else {
            long http_code;
            curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
            
            if (http_code == 200) {
                printf("请求成功!\n");
                printf("状态码: %ld\n", http_code);
                printf("响应内容: %s\n", response.data);
                
                // 解析JSON(使用json-c库)
                json_object *json_response = json_tokener_parse(response.data);
                if (json_response != NULL) {
                    printf("JSON解析成功\n");
                    
                    // 获取data字段
                    json_object *data_obj;
                    if (json_object_object_get_ex(json_response, "data", &data_obj)) {
                        if (json_object_is_type(data_obj, json_type_array)) {
                            int array_len = json_object_array_length(data_obj);
                            printf("数据条数: %d\n", array_len);
                            
                            // 显示前几条数据
                            int display_count = (array_len < 3) ? array_len : 3;
                            for (int i = 0; i < display_count; i++) {
                                json_object *item = json_object_array_get_idx(data_obj, i);
                                printf("第%d条数据: %s\n", i + 1, json_object_to_json_string(item));
                            }
                        }
                    }
                    
                    // 检查错误信息
                    json_object *error_obj;
                    if (json_object_object_get_ex(json_response, "error", &error_obj)) {
                        printf("API错误: %s\n", json_object_get_string(error_obj));
                    }
                    
                    // 释放JSON对象
                    json_object_put(json_response);
                } else {
                    printf("JSON解析失败\n");
                }
            } else {
                printf("请求失败,状态码: %ld\n", http_code);
                printf("响应内容: %s\n", response.data);
            }
        }
        
        // 清理
        curl_slist_free_all(headers);
        curl_easy_cleanup(curl);
    } else {
        printf("初始化curl失败\n");
    }
    
    // 释放响应数据内存
    if (response.data) {
        free(response.data);
    }
    
    curl_global_cleanup();
    return 0;
}
      

使用标准库(不依赖第三方库)


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifdef _WIN32
    #include <windows.h>
    #include <wininet.h>
    #pragma comment(lib, "wininet.lib")
#else
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <netdb.h>
    #include <unistd.h>
    #include <arpa/inet.h>
#endif

#ifdef _WIN32
int windows_http_request() {
    HINTERNET hInternet, hConnect, hRequest;
    DWORD dwSize = 0;
    DWORD dwDownloaded = 0;
    LPSTR pszOutBuffer;
    BOOL bResults = FALSE;
    
    // API 配置
    const char *server = "stockapi.com.cn";
    const char *token = "你的token"; // 请替换为实际的token
    
    char path[1024];
    snprintf(path, sizeof(path), 
        "/v1/base/day?token=%s&code=600004&startDate=2021-10-10&endDate=2021-10-15&calculationCycle=100",
        token);
    
    printf("正在发送请求...\n");
    printf("服务器: %s\n", server);
    printf("路径: %s\n", path);
    
    // 初始化WinINet
    hInternet = InternetOpenA("C-WinINet-StockAPI-Client/1.0",
                             INTERNET_OPEN_TYPE_PRECONFIG,
                             NULL, NULL, 0);
    
    if (hInternet) {
        hConnect = InternetConnectA(hInternet, server,
                                   INTERNET_DEFAULT_HTTPS_PORT,
                                   NULL, NULL, INTERNET_SERVICE_HTTP, 0, 1);
        
        if (hConnect) {
            hRequest = HttpOpenRequestA(hConnect, "GET", path,
                                       NULL, NULL, NULL,
                                       INTERNET_FLAG_SECURE, 1);
            
            if (hRequest) {
                // 发送请求
                bResults = HttpSendRequestA(hRequest, NULL, 0, NULL, 0);
                
                if (bResults) {
                    // 查询响应大小
                    if (!HttpQueryInfoA(hRequest, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER,
                                       (LPVOID)&dwSize, &dwSize, NULL)) {
                        dwSize = 0;
                    }
                    
                    // 分配缓冲区
                    pszOutBuffer = (LPSTR)malloc(dwSize + 1);
                    if (pszOutBuffer) {
                        ZeroMemory(pszOutBuffer, dwSize + 1);
                        
                        // 读取数据
                        if (InternetReadFile(hRequest, (LPVOID)pszOutBuffer, dwSize, &dwDownloaded)) {
                            printf("请求成功!\n");
                            printf("响应内容: %s\n", pszOutBuffer);
                        }
                        
                        free(pszOutBuffer);
                    }
                } else {
                    printf("发送请求失败\n");
                }
                
                InternetCloseHandle(hRequest);
            }
            
            InternetCloseHandle(hConnect);
        }
        
        InternetCloseHandle(hInternet);
    }
    
    return 0;
}
#endif

int main() {
#ifdef _WIN32
    return windows_http_request();
#else
    printf("此示例在Linux/Unix系统上需要使用libcurl库\n");
    printf("请使用上面的libcurl示例代码\n");
    return 1;
#endif
}
      

编译说明

使用 libcurl 和 json-c(推荐)


# Ubuntu/Debian
sudo apt-get update
sudo apt-get install libcurl4-openssl-dev libjson-c-dev

# 编译
gcc -std=c99 -o stock_api main.c -lcurl -ljson-c

# CentOS/RHEL
sudo yum install libcurl-devel json-c-devel
# 或者使用 dnf (较新版本)
sudo dnf install libcurl-devel json-c-devel

# 编译
gcc -std=c99 -o stock_api main.c -lcurl -ljson-c

# macOS (使用 Homebrew)
brew install curl json-c
gcc -std=c99 -o stock_api main.c -lcurl -ljson-c
      

Windows 编译(使用 MinGW)


# 安装 MSYS2 和 MinGW
# 然后安装依赖
pacman -S mingw-w64-x86_64-curl mingw-w64-x86_64-json-c

# 编译 libcurl 版本
gcc -std=c99 -o stock_api.exe main.c -lcurl -ljson-c

# 编译 WinINet 版本(仅Windows标准库)
gcc -std=c99 -o stock_api_wininet.exe main_wininet.c -lwininet
      

使用 CMake


cmake_minimum_required(VERSION 3.10)
project(StockAPIDemo C)

set(CMAKE_C_STANDARD 99)
set(CMAKE_C_STANDARD_REQUIRED ON)

# 查找依赖库
find_package(PkgConfig REQUIRED)
pkg_check_modules(CURL REQUIRED libcurl)
pkg_check_modules(JSON_C REQUIRED json-c)

# libcurl 版本
add_executable(stock_api_curl main_curl.c)
target_link_libraries(stock_api_curl ${CURL_LIBRARIES} ${JSON_C_LIBRARIES})
target_include_directories(stock_api_curl PRIVATE ${CURL_INCLUDE_DIRS} ${JSON_C_INCLUDE_DIRS})

# Windows WinINet 版本
if(WIN32)
    add_executable(stock_api_wininet main_wininet.c)
    target_link_libraries(stock_api_wininet wininet)
endif()
      

Makefile 示例


CC=gcc
CFLAGS=-std=c99 -Wall -Wextra
LIBS_CURL=-lcurl -ljson-c
LIBS_WININET=-lwininet

# 默认目标
all: stock_api_curl

# libcurl 版本
stock_api_curl: main_curl.c
	$(CC) $(CFLAGS) -o $@ $< $(LIBS_CURL)

# Windows WinINet 版本
stock_api_wininet: main_wininet.c
	$(CC) $(CFLAGS) -o $@ $< $(LIBS_WININET)

# 清理
clean:
	rm -f stock_api_curl stock_api_wininet *.exe

.PHONY: all clean
      

Node.js 示例代码

使用 axios 库(推荐)


const axios = require('axios');

// API 配置
const BASE_URL = 'https://stockapi.com.cn/v1/base/day';
const TOKEN = '你的token'; // 请替换为实际的token

// 请求参数
const params = {
    token: TOKEN,
    code: '600004',
    startDate: '2021-10-10',
    endDate: '2021-10-15',
    calculationCycle: 100
};

async function fetchStockData() {
    try {
        console.log('正在发送请求...');
        console.log('请求URL:', BASE_URL);
        console.log('请求参数:', params);
        
        const response = await axios.get(BASE_URL, {
            params: params,
            timeout: 30000, // 30秒超时
            headers: {
                'User-Agent': 'Node.js-StockAPI-Client/1.0',
                'Accept': 'application/json'
            }
        });
        
        console.log('请求成功!');
        console.log('状态码:', response.status);
        console.log('响应头:', response.headers);
        
        const data = response.data;
        console.log('响应数据:', JSON.stringify(data, null, 2));
        
        // 处理响应数据
        if (data.data && Array.isArray(data.data)) {
            console.log(`\n数据条数: ${data.data.length}`);
            
            // 显示前3条数据
            const displayCount = Math.min(3, data.data.length);
            for (let i = 0; i < displayCount; i++) {
                console.log(`第${i + 1}条数据:`, data.data[i]);
            }
        }
        
        // 检查错误信息
        if (data.error) {
            console.error('API错误:', data.error);
        }
        
        return data;
        
    } catch (error) {
        console.error('请求失败:', error.message);
        
        if (error.response) {
            // 服务器响应了错误状态码
            console.error('错误状态码:', error.response.status);
            console.error('错误响应:', error.response.data);
        } else if (error.request) {
            // 请求已发出但没有收到响应
            console.error('网络错误或超时');
        } else {
            // 其他错误
            console.error('请求配置错误:', error.message);
        }
        
        throw error;
    }
}

// 执行请求
fetchStockData()
    .then(data => {
        console.log('\n数据获取完成');
    })
    .catch(error => {
        console.error('程序执行失败:', error.message);
        process.exit(1);
    });
      

使用内置 https 模块


const https = require('https');
const querystring = require('querystring');

// API 配置
const BASE_URL = 'stockapi.com.cn';
const PATH = '/v1/base/day';
const TOKEN = '你的token'; // 请替换为实际的token

// 请求参数
const params = {
    token: TOKEN,
    code: '600004',
    startDate: '2021-10-10',
    endDate: '2021-10-15',
    calculationCycle: 100
};

function fetchStockData() {
    return new Promise((resolve, reject) => {
        const queryString = querystring.stringify(params);
        const fullPath = `${PATH}?${queryString}`;
        
        console.log('正在发送请求...');
        console.log('请求URL:', `https://${BASE_URL}${fullPath}`);
        
        const options = {
            hostname: BASE_URL,
            path: fullPath,
            method: 'GET',
            headers: {
                'User-Agent': 'Node.js-HTTPS-StockAPI-Client/1.0',
                'Accept': 'application/json'
            },
            timeout: 30000 // 30秒超时
        };
        
        const req = https.request(options, (res) => {
            console.log('请求成功!');
            console.log('状态码:', res.statusCode);
            console.log('响应头:', res.headers);
            
            let data = '';
            
            res.on('data', (chunk) => {
                data += chunk;
            });
            
            res.on('end', () => {
                try {
                    const jsonData = JSON.parse(data);
                    console.log('响应数据:', JSON.stringify(jsonData, null, 2));
                    
                    // 处理响应数据
                    if (jsonData.data && Array.isArray(jsonData.data)) {
                        console.log(`\n数据条数: ${jsonData.data.length}`);
                        
                        // 显示前3条数据
                        const displayCount = Math.min(3, jsonData.data.length);
                        for (let i = 0; i < displayCount; i++) {
                            console.log(`第${i + 1}条数据:`, jsonData.data[i]);
                        }
                    }
                    
                    // 检查错误信息
                    if (jsonData.error) {
                        console.error('API错误:', jsonData.error);
                    }
                    
                    resolve(jsonData);
                    
                } catch (parseError) {
                    console.error('JSON解析失败:', parseError.message);
                    console.error('原始响应:', data);
                    reject(parseError);
                }
            });
        });
        
        req.on('error', (error) => {
            console.error('请求失败:', error.message);
            reject(error);
        });
        
        req.on('timeout', () => {
            console.error('请求超时');
            req.destroy();
            reject(new Error('Request timeout'));
        });
        
        req.end();
    });
}

// 执行请求
fetchStockData()
    .then(data => {
        console.log('\n数据获取完成');
    })
    .catch(error => {
        console.error('程序执行失败:', error.message);
        process.exit(1);
    });
      

使用 node-fetch 库


const fetch = require('node-fetch');

// API 配置
const BASE_URL = 'https://stockapi.com.cn/v1/base/day';
const TOKEN = '你的token'; // 请替换为实际的token

// 构建请求URL
const params = new URLSearchParams({
    token: TOKEN,
    code: '600004',
    startDate: '2021-10-10',
    endDate: '2021-10-15',
    calculationCycle: 100
});

const requestUrl = `${BASE_URL}?${params.toString()}`;

async function fetchStockData() {
    try {
        console.log('正在发送请求...');
        console.log('请求URL:', requestUrl);
        
        const response = await fetch(requestUrl, {
            method: 'GET',
            headers: {
                'User-Agent': 'Node.js-Fetch-StockAPI-Client/1.0',
                'Accept': 'application/json'
            },
            timeout: 30000 // 30秒超时
        });
        
        console.log('请求成功!');
        console.log('状态码:', response.status);
        console.log('状态文本:', response.statusText);
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const data = await response.json();
        console.log('响应数据:', JSON.stringify(data, null, 2));
        
        // 处理响应数据
        if (data.data && Array.isArray(data.data)) {
            console.log(`\n数据条数: ${data.data.length}`);
            
            // 显示前3条数据
            const displayCount = Math.min(3, data.data.length);
            for (let i = 0; i < displayCount; i++) {
                console.log(`第${i + 1}条数据:`, data.data[i]);
            }
        }
        
        // 检查错误信息
        if (data.error) {
            console.error('API错误:', data.error);
        }
        
        return data;
        
    } catch (error) {
        console.error('请求失败:', error.message);
        
        if (error.name === 'FetchError') {
            console.error('网络错误或超时');
        }
        
        throw error;
    }
}

// 执行请求
fetchStockData()
    .then(data => {
        console.log('\n数据获取完成');
    })
    .catch(error => {
        console.error('程序执行失败:', error.message);
        process.exit(1);
    });
      

Express.js 服务器示例


const express = require('express');
const axios = require('axios');
const cors = require('cors');

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件
app.use(cors());
app.use(express.json());

// API 配置
const STOCK_API_BASE_URL = 'https://stockapi.com.cn/v1/base/day';
const TOKEN = process.env.STOCK_API_TOKEN || '你的token'; // 建议使用环境变量

// 股票数据接口
app.get('/api/stock/:code', async (req, res) => {
    try {
        const { code } = req.params;
        const { startDate, endDate, calculationCycle = 100 } = req.query;
        
        // 参数验证
        if (!code) {
            return res.status(400).json({ error: '股票代码不能为空' });
        }
        
        if (!startDate || !endDate) {
            return res.status(400).json({ error: '开始日期和结束日期不能为空' });
        }
        
        console.log(`正在获取股票 ${code} 的数据...`);
        
        const params = {
            token: TOKEN,
            code: code,
            startDate: startDate,
            endDate: endDate,
            calculationCycle: calculationCycle
        };
        
        const response = await axios.get(STOCK_API_BASE_URL, {
            params: params,
            timeout: 30000,
            headers: {
                'User-Agent': 'Express-StockAPI-Server/1.0'
            }
        });
        
        console.log(`股票 ${code} 数据获取成功`);
        
        // 返回数据
        res.json({
            success: true,
            data: response.data,
            timestamp: new Date().toISOString()
        });
        
    } catch (error) {
        console.error('获取股票数据失败:', error.message);
        
        if (error.response) {
            // API 返回错误
            res.status(error.response.status).json({
                success: false,
                error: error.response.data || '股票API返回错误',
                timestamp: new Date().toISOString()
            });
        } else {
            // 网络或其他错误
            res.status(500).json({
                success: false,
                error: '服务器内部错误',
                timestamp: new Date().toISOString()
            });
        }
    }
});

// 健康检查接口
app.get('/health', (req, res) => {
    res.json({
        status: 'OK',
        timestamp: new Date().toISOString(),
        uptime: process.uptime()
    });
});

// 启动服务器
app.listen(PORT, () => {
    console.log(`股票API服务器运行在端口 ${PORT}`);
    console.log(`健康检查: http://localhost:${PORT}/health`);
    console.log(`股票数据API: http://localhost:${PORT}/api/stock/{code}?startDate=2021-10-10&endDate=2021-10-15`);
});

// 优雅关闭
process.on('SIGTERM', () => {
    console.log('收到SIGTERM信号,正在关闭服务器...');
    process.exit(0);
});

process.on('SIGINT', () => {
    console.log('收到SIGINT信号,正在关闭服务器...');
    process.exit(0);
});
      

依赖安装和运行说明

package.json 示例


{
  "name": "stock-api-demo",
  "version": "1.0.0",
  "description": "股票API Node.js示例",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "dev": "nodemon index.js",
    "test": "node test.js"
  },
  "dependencies": {
    "axios": "^1.6.0",
    "node-fetch": "^2.7.0",
    "express": "^4.18.0",
    "cors": "^2.8.5"
  },
  "devDependencies": {
    "nodemon": "^3.0.0"
  },
  "keywords": ["stock", "api", "nodejs", "demo"],
  "author": "Your Name",
  "license": "MIT"
}
      

安装和运行


# 初始化项目
npm init -y

# 安装依赖
npm install axios node-fetch express cors

# 安装开发依赖(可选)
npm install --save-dev nodemon

# 运行axios示例
node axios-example.js

# 运行https模块示例
node https-example.js

# 运行node-fetch示例
node fetch-example.js

# 运行Express服务器
node server.js

# 使用nodemon开发模式运行(自动重启)
npx nodemon server.js
      

环境变量配置


# 创建 .env 文件
echo "STOCK_API_TOKEN=你的实际token" > .env

# 安装dotenv库读取环境变量
npm install dotenv

# 在代码中使用
require('dotenv').config();
const TOKEN = process.env.STOCK_API_TOKEN;
      

注意事项

  • Python:请确保已安装 requests 库:pip install requests
  • Java:推荐使用 OkHttp 库,需要添加相应的 Maven 或 Gradle 依赖
  • PHP:确保启用了cURL扩展,或者使用file_get_contents时启用了allow_url_fopen
  • PHP:使用Guzzle库时需要通过Composer安装:composer require guzzlehttp/guzzle
  • C++:需要安装libcurl和jsoncpp开发库,或者使用cpprestsdk库
  • C++:建议使用CMake进行项目管理,确保正确链接所需的库文件
  • C++:在Windows环境下可以使用vcpkg包管理器安装依赖:vcpkg install curl jsoncpp cpprestsdk
  • C#:推荐使用HttpClient进行异步HTTP请求,需要安装Newtonsoft.Json包处理JSON
  • C#:使用RestSharp库可以简化HTTP请求代码,通过NuGet安装相关依赖包
  • C#:项目需要.NET Framework 4.6.1+或.NET Core 2.0+/.NET 5+支持
  • C语言:推荐使用libcurl库进行HTTP请求,配合json-c库解析JSON数据
  • C语言:在Windows环境下可以使用WinINet API(仅限Windows系统),或使用MSYS2/MinGW安装libcurl
  • C语言:编译时需要链接相应的库文件(-lcurl -ljson-c),注意内存管理,及时释放分配的内存资源
  • Node.js:推荐使用axios库进行HTTP请求,需要通过npm安装:npm install axios
  • Node.js:可以使用内置的https模块,无需额外依赖,适合轻量级应用
  • Node.js:node-fetch库提供类似浏览器fetch API的体验,Express.js适合构建API服务器
  • Node.js:建议使用环境变量管理API token,可以安装dotenv库:npm install dotenv
  • 请将示例代码中的 "你的token" 替换为实际的API访问令牌
  • 股票代码需要使用正确的格式(如:600004)
  • 日期格式必须为 YYYY-MM-DD
  • 请注意API的调用频率限制
  • 建议设置合适的连接超时和读取超时时间
  • 注意处理字符编码,使用 UTF-8
  • 在生产环境中,建议使用环境变量或配置文件来管理API token

错误处理

常见的错误响应:


{
  "msg": "亲!您传入的token不存在,请检查token是否正确。地址:https://stockapi.com.cn/",
  "code": 60048
}
      

请确保:

  • Token 有效且正确
  • 网络连接正常
  • 请求参数格式正确
钉钉二维码
添加钉钉联系技术
飞书二维码
添加飞书联系技术
公众号二维码
关注微信公众号获取更多资讯