请求交互
- Java
- Python
package com.weex.lcp.utils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class ApiClient {
// API信息
private static final String API_KEY = ""; // 替换为实际的 API Key
private static final String SECRET_KEY = ""; // 替换为实际的 Secret Key
private static final String ACCESS_PASSPHRASE = ""; // 替换为实际的 Access Passphrase
private static final String BASE_URL = ""; // 替换为实际的 API 地址
// 生成签名(POST请求)
public static String generateSignature(String secretKey, String timestamp, String method, String requestPath, String queryString, String body) throws Exception {
String message = timestamp + method.toUpperCase() + requestPath + queryString + body;
return generateHmacSha256Signature(secretKey, message);
}
// 生成签名(GET请求)
public static String generateSignatureGet(String secretKey, String timestamp, String method, String requestPath, String queryString) throws Exception {
String message = timestamp + method.toUpperCase() + requestPath + queryString;
return generateHmacSha256Signature(secretKey, message);
}
// 生成 HMAC SHA256 签名
private static String generateHmacSha256Signature(String secretKey, String message) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(secretKeySpec);
byte[] signatureBytes = mac.doFinal(message.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(signatureBytes);
}
// 发送 POST 请求
public static String sendRequestPost(String apiKey, String secretKey, String accessPassphrase, String method, String requestPath, String queryString, String body) throws Exception {
String timestamp = String.valueOf(System.currentTimeMillis());
String signature = generateSignature(secretKey, timestamp, method, requestPath, queryString, body);
HttpPost postRequest = new HttpPost(BASE_URL + requestPath);
postRequest.setHeader("ACCESS-KEY", apiKey);
postRequest.setHeader("ACCESS-SIGN", signature);
postRequest.setHeader("ACCESS-TIMESTAMP", timestamp);
postRequest.setHeader("ACCESS-PASSPHRASE", accessPassphrase);
postRequest.setHeader("Content-Type", "application/json");
postRequest.setHeader("locale", "zh-CN");
StringEntity entity = new StringEntity(body, StandardCharsets.UTF_8);
postRequest.setEntity(entity);
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
CloseableHttpResponse response = httpClient.execute(postRequest);
return EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
}
}
// 发送 GET 请求
public static String sendRequestGet(String apiKey, String secretKey, String accessPassphrase, String method, String requestPath, String queryString) throws Exception {
String timestamp = String.valueOf(System.currentTimeMillis());
String signature = generateSignatureGet(secretKey, timestamp, method, requestPath, queryString);
HttpGet getRequest = new HttpGet(BASE_URL + requestPath+queryString);
getRequest.setHeader("ACCESS-KEY", apiKey);
getRequest.setHeader("ACCESS-SIGN", signature);
getRequest.setHeader("ACCESS-TIMESTAMP", timestamp);
getRequest.setHeader("ACCESS-PASSPHRASE", accessPassphrase);
getRequest.setHeader("Content-Type", "application/json");
getRequest.setHeader("locale", "zh-CN");
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
CloseableHttpResponse response = httpClient.execute(getRequest);
return EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
}
}
// 示例调用
public static void main(String[] args) {
try {
// GET 请求示例
String requestPath = "/api/uni/v3/order/currentPlan";
String queryString = "?symbol=cmt_bchusdt&delegateType=0&startTime=1742213127794&endTime=1742213506548";
String response = sendRequestGet(API_KEY, SECRET_KEY, ACCESS_PASSPHRASE, "GET", requestPath, queryString);
System.out.println("GET Response: " + response);
// POST 请求示例
String body = "{\"symbol\": \"ETHUSDT_SPBL\", \"limit\": \"2\"}";
response = sendRequestPost(API_KEY, SECRET_KEY, ACCESS_PASSPHRASE, "POST", requestPath, "", body);
System.out.println("POST Response: " + response);
} catch (Exception e) {
e.printStackTrace();
}
}
}
import time
import hmac
import hashlib
import base64
import requests
import json
api_key = ""
secret_key = ""
access_passphrase = ""
def generate_signature(secret_key, timestamp, method, request_path, query_string, body):
message = timestamp + method.upper() + request_path + query_string + str(body)
signature = hmac.new(secret_key.encode(), message.encode(), hashlib.sha256).digest()
# print(base64.b64encode(signature).decode())
return base64.b64encode(signature).decode()
def generate_signature_get(secret_key, timestamp, method, request_path, query_string):
message = timestamp + method.upper() + request_path + query_string
signature = hmac.new(secret_key.encode(), message.encode(), hashlib.sha256).digest()
# print(base64.b64encode(signature).decode())
return base64.b64encode(signature).decode()
def send_request_post(api_key, secret_key, access_passphrase, method, request_path, query_string, body):
timestamp = str(int(time.time() * 1000))
# print(timestamp)
body = json.dumps(body)
signature = generate_signature(secret_key, timestamp, method, request_path, query_string, body)
headers = {
"ACCESS-KEY": api_key,
"ACCESS-SIGN": signature,
"ACCESS-TIMESTAMP": timestamp,
"ACCESS-PASSPHRASE": access_passphrase,
"Content-Type": "application/json",
"locale": "zh-CN"
}
url = "https://contract-openapi.weex.com" # 请替换为实际的API地址
if method == "GET":
response = requests.get(url + request_path, headers=headers)
elif method == "POST":
response = requests.post(url + request_path, headers=headers, data=body)
return response
def send_request_get(api_key, secret_key, access_passphrase, method, request_path, query_string):
timestamp = str(int(time.time() * 1000))
# print(timestamp)
signature = generate_signature_get(secret_key, timestamp, method, request_path, query_string)
headers = {
"ACCESS-KEY": api_key,
"ACCESS-SIGN": signature,
"ACCESS-TIMESTAMP": timestamp,
"ACCESS-PASSPHRASE": access_passphrase,
"Content-Type": "application/json",
"locale": "zh-CN"
}
url = "https://contract-openapi.weex.com" # 请替换为实际的API地址
if method == "GET":
response = requests.get(url + request_path, headers=headers)
return response
# 示例调用 GET 请求
request_path = "/api/spot/v1/account/assets"
# request_path = "/api/spot/v1/public/currencies" # 查看币对列表
query_string = ''
body = ''
response = send_request_get(api_key, secret_key, access_passphrase, "GET", request_path, query_string)
# 示例调用 POST 请求
# request_path = "/api/spot/v1/trade/fills"
# body = {"symbol": "ETHUSDT_SPBL", "limit": "2"}
# query_string = ""
# response = send_request_post(api_key, secret_key, access_passphrase, "POST", request_path, query_string, body)
print(response.status_code)
print(response.text)
所有请求基于Https协议,请求头信息中Content-Type 需要统一设置为: 'application/json'。
请求交互说明
- 请求参数:根据接口请求参数规定进行参数封装。
- 提交请求参数:将封装好的请求参数通过GET/POST方式提交至服务器。
- 服务器响应:服务器首先对用户请求数据进行参数安全校验,通过校验后根据业务逻辑将响应数据以JSON格式返回给用户。
- 数据处理:对服务器响应数据进行处理。
成功
HTTP状态码200表示成功响应,并可能包含内容。如果响应含有内容,则将显示在相应的返回内容里面。
常见错误码
- 400 Bad Request – Invalid request format 请求格式无效
- 401 Unauthorized – Invalid API Key 无效的API Key
- 403 Forbidden – You do not have access to the requested resource 请求无权限
- 404 Not Found 没有找到请求
- 429 Too Many Requests 请求太频繁被系统限流
- 500 Internal Server Error – We had a problem with our server 服务器内部错误
- 如果失败body带有错误描述信息