> For the complete documentation index, see [llms.txt](https://docs.infoway.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.infoway.io/rest-api/http-code-example.md).

# HTTP请求示例

以下示例均以股票接口为例。换市场只需替换路径中的 `stock`，可选 `japan` / `india` / `korea` / `taiwan` / `crypto` / `common`。

所有接口都通过请求头 `apiKey` 鉴权。

## 实时成交明细（Trade）

`GET /stock/batch_trade/{codes}`

{% tabs %}
{% tab title="Go" %}

```go
package main

import (
	"fmt"
	"io"
	"net/http"
	"time"
)

func main() {
	// 逗号分隔，最多 100 个产品
	apiURL := "https://data.infoway.io/stock/batch_trade/TSLA.US,AAPL.US"

	req, err := http.NewRequest("GET", apiURL, nil)
	if err != nil {
		fmt.Println("Error creating request:", err)
		return
	}
	req.Header.Set("Accept", "application/json")
	req.Header.Set("apiKey", "yourApikey")

	client := &http.Client{Timeout: 10 * time.Second}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error sending request:", err)
		return
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error reading response:", err)
		return
	}

	fmt.Printf("HTTP code: %d\n", resp.StatusCode)
	fmt.Printf("message: %s\n", body)
}
```

{% endtab %}

{% tab title="Java" %}

```java
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

public class TradeExample {
    public static void main(String[] args) throws IOException, InterruptedException {
        // 逗号分隔，最多 100 个产品
        String apiUrl = "https://data.infoway.io/stock/batch_trade/TSLA.US,AAPL.US";

        HttpClient client = HttpClient.newBuilder()
                .connectTimeout(Duration.ofSeconds(10))
                .build();

        HttpRequest request = HttpRequest.newBuilder(URI.create(apiUrl))
                .timeout(Duration.ofSeconds(10))
                .header("Accept", "application/json")
                .header("apiKey", "yourApikey")
                .GET()
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println("HTTP code: " + response.statusCode());
        System.out.println("message: " + response.body());
    }
}
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
// Node.js 18+ 或浏览器原生 fetch（需顶层 await，Node 下保存为 .mjs）
// 逗号分隔，最多 100 个产品
const apiUrl = 'https://data.infoway.io/stock/batch_trade/TSLA.US,AAPL.US';

const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 10000);

try {
  const response = await fetch(apiUrl, {
    method: 'GET',
    headers: {
      Accept: 'application/json',
      apiKey: 'yourApikey',
    },
    signal: controller.signal,
  });

  console.log(`HTTP code: ${response.status}`);
  console.log(`message: ${await response.text()}`);
} catch (err) {
  console.error('Error sending request:', err);
} finally {
  clearTimeout(timer);
}
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
// 逗号分隔，最多 100 个产品
$apiUrl = 'https://data.infoway.io/stock/batch_trade/TSLA.US,AAPL.US';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Accept: application/json',
    'apiKey: yourApikey',
]);

$response = curl_exec($ch);
if ($response === false) {
    echo 'Error sending request: ' . curl_error($ch) . PHP_EOL;
    curl_close($ch);
    exit(1);
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

echo "HTTP code: $httpCode" . PHP_EOL;
echo "message: $response" . PHP_EOL;
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

# 逗号分隔，最多 100 个产品
api_url = 'https://data.infoway.io/stock/batch_trade/TSLA.US,AAPL.US'

headers = {
    'Accept': 'application/json',
    'apiKey': 'yourApikey',
}

response = requests.get(api_url, headers=headers, timeout=10)

print(f"HTTP code: {response.status_code}")
print(f"message: {response.text}")
```

{% endtab %}
{% endtabs %}

## 实时买卖盘口（Depth）

`GET /stock/batch_depth/{codes}`

{% tabs %}
{% tab title="Go" %}

```go
package main

import (
	"fmt"
	"io"
	"net/http"
	"time"
)

func main() {
	// 逗号分隔，最多 100 个产品
	apiURL := "https://data.infoway.io/stock/batch_depth/TSLA.US,AAPL.US"

	req, err := http.NewRequest("GET", apiURL, nil)
	if err != nil {
		fmt.Println("Error creating request:", err)
		return
	}
	req.Header.Set("Accept", "application/json")
	req.Header.Set("apiKey", "yourApikey")

	client := &http.Client{Timeout: 10 * time.Second}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error sending request:", err)
		return
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error reading response:", err)
		return
	}

	fmt.Printf("HTTP code: %d\n", resp.StatusCode)
	fmt.Printf("message: %s\n", body)
}
```

{% endtab %}

{% tab title="Java" %}

```java
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

public class DepthExample {
    public static void main(String[] args) throws IOException, InterruptedException {
        // 逗号分隔，最多 100 个产品
        String apiUrl = "https://data.infoway.io/stock/batch_depth/TSLA.US,AAPL.US";

        HttpClient client = HttpClient.newBuilder()
                .connectTimeout(Duration.ofSeconds(10))
                .build();

        HttpRequest request = HttpRequest.newBuilder(URI.create(apiUrl))
                .timeout(Duration.ofSeconds(10))
                .header("Accept", "application/json")
                .header("apiKey", "yourApikey")
                .GET()
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println("HTTP code: " + response.statusCode());
        System.out.println("message: " + response.body());
    }
}
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
// Node.js 18+ 或浏览器原生 fetch（需顶层 await，Node 下保存为 .mjs）
// 逗号分隔，最多 100 个产品
const apiUrl = 'https://data.infoway.io/stock/batch_depth/TSLA.US,AAPL.US';

const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 10000);

try {
  const response = await fetch(apiUrl, {
    method: 'GET',
    headers: {
      Accept: 'application/json',
      apiKey: 'yourApikey',
    },
    signal: controller.signal,
  });

  console.log(`HTTP code: ${response.status}`);
  console.log(`message: ${await response.text()}`);
} catch (err) {
  console.error('Error sending request:', err);
} finally {
  clearTimeout(timer);
}
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
// 逗号分隔，最多 100 个产品
$apiUrl = 'https://data.infoway.io/stock/batch_depth/TSLA.US,AAPL.US';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Accept: application/json',
    'apiKey: yourApikey',
]);

$response = curl_exec($ch);
if ($response === false) {
    echo 'Error sending request: ' . curl_error($ch) . PHP_EOL;
    curl_close($ch);
    exit(1);
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

echo "HTTP code: $httpCode" . PHP_EOL;
echo "message: $response" . PHP_EOL;
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

# 逗号分隔，最多 100 个产品
api_url = 'https://data.infoway.io/stock/batch_depth/TSLA.US,AAPL.US'

headers = {
    'Accept': 'application/json',
    'apiKey': 'yourApikey',
}

response = requests.get(api_url, headers=headers, timeout=10)

print(f"HTTP code: {response.status_code}")
print(f"message: {response.text}")
```

{% endtab %}
{% endtabs %}

## 历史 / 实时 K 线（Candles）

`POST /stock/v2/batch_kline`

{% tabs %}
{% tab title="Go" %}

```go
package main

import (
	"bytes"
	"fmt"
	"io"
	"net/http"
	"time"
)

func main() {
	apiURL := "https://data.infoway.io/stock/v2/batch_kline"

	// 单个产品最多 500 根；同时查多个产品时每个只返回最近 2 根
	payload := []byte(`{"klineType":1,"klineNum":500,"codes":"TSLA.US"}`)

	req, err := http.NewRequest("POST", apiURL, bytes.NewReader(payload))
	if err != nil {
		fmt.Println("Error creating request:", err)
		return
	}
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Accept", "application/json")
	req.Header.Set("apiKey", "yourApikey")

	client := &http.Client{Timeout: 10 * time.Second}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error sending request:", err)
		return
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error reading response:", err)
		return
	}

	fmt.Printf("HTTP code: %d\n", resp.StatusCode)
	fmt.Printf("message: %s\n", body)
}
```

{% endtab %}

{% tab title="Java" %}

```java
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

public class KlineExample {
    public static void main(String[] args) throws IOException, InterruptedException {
        String apiUrl = "https://data.infoway.io/stock/v2/batch_kline";

        // 单个产品最多 500 根；同时查多个产品时每个只返回最近 2 根
        String payload = "{\"klineType\":1,\"klineNum\":500,\"codes\":\"TSLA.US\"}";

        HttpClient client = HttpClient.newBuilder()
                .connectTimeout(Duration.ofSeconds(10))
                .build();

        HttpRequest request = HttpRequest.newBuilder(URI.create(apiUrl))
                .timeout(Duration.ofSeconds(10))
                .header("Content-Type", "application/json")
                .header("Accept", "application/json")
                .header("apiKey", "yourApikey")
                .POST(HttpRequest.BodyPublishers.ofString(payload))
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println("HTTP code: " + response.statusCode());
        System.out.println("message: " + response.body());
    }
}
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
// Node.js 18+ 或浏览器原生 fetch（需顶层 await，Node 下保存为 .mjs）
// 单个产品最多 500 根；同时查多个产品时每个只返回最近 2 根
const apiUrl = 'https://data.infoway.io/stock/v2/batch_kline';

const payload = {
  klineType: 1,
  klineNum: 500,
  codes: 'TSLA.US',
};

const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 10000);

try {
  const response = await fetch(apiUrl, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Accept: 'application/json',
      apiKey: 'yourApikey',
    },
    body: JSON.stringify(payload),
    signal: controller.signal,
  });

  console.log(`HTTP code: ${response.status}`);
  console.log(`message: ${await response.text()}`);
} catch (err) {
  console.error('Error sending request:', err);
} finally {
  clearTimeout(timer);
}
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
$apiUrl = 'https://data.infoway.io/stock/v2/batch_kline';

// 单个产品最多 500 根；同时查多个产品时每个只返回最近 2 根
$payload = json_encode([
    'klineType' => 1,
    'klineNum'  => 500,
    'codes'     => 'TSLA.US',
]);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Accept: application/json',
    'apiKey: yourApikey',
]);

$response = curl_exec($ch);
if ($response === false) {
    echo 'Error sending request: ' . curl_error($ch) . PHP_EOL;
    curl_close($ch);
    exit(1);
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

echo "HTTP code: $httpCode" . PHP_EOL;
echo "message: $response" . PHP_EOL;
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

api_url = 'https://data.infoway.io/stock/v2/batch_kline'

headers = {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'apiKey': 'yourApikey',
}

# 单个产品最多 500 根；同时查多个产品时每个只返回最近 2 根
payload = {
    'klineType': 1,
    'klineNum': 500,
    'codes': 'TSLA.US',
}

response = requests.post(api_url, json=payload, headers=headers, timeout=10)

print(f"HTTP code: {response.status_code}")
print(f"message: {response.text}")
```

{% endtab %}
{% endtabs %}
