Java查询期货天然气实时行情价格
使用HTTP请求,查询天然气实时行情价格:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpJavaExample {
public static void main(String[] args) {
try {
/*
Encode the following JSON into URL format and copy it to the query field of the HTTP request
{"trace" : "java_http_test1","data" : {"code" : "XNGUSD","kline_type" : 1,"kline_timestamp_end" : 0,"query_kline_num" : 2,"adjust_type": 0}}
Special Note:
GitHub: https://github.com/alltick/realtime-forex-crypto-stock-tick-finance-websocket-api
Token Application: https://alltick.io
Replace "testtoken" in the URL below with your own token
API addresses for forex, cryptocurrencies, and precious metals:
https://quote.tradeswitcher.com/quote-b-api
*/
String url = "http://quote.tradeswitcher.com/quote-b-api/kline?token=testtoken&query=%7B%22trace%22%20%3A%20%22java_http_test1%22%2C%22data%22%20%3A%20%7B%22code%22%20%3A%20%22XNGUSD%22%2C%22kline_type%22%20%3A%201%2C%22kline_timestamp_end%22%20%3A%200%2C%22query_kline_num%22%20%3A%202%2C%22adjust_type%22%3A%200%7D%7D";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
System.out.println("Response Code: " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
主要逻辑:
- 构建请求URL:指定API地址、身份认证令牌(token),以及查询参数(包括数据代码、K线类型等)。
- 创建HTTP连接:使用Java的
HttpURLConnection
类建立到API的HTTP连接。 - 设置请求方法:将请求方式设为GET,以获取数据。
- 发送请求并获取响应代码:发送请求并获取服务器返回的响应代码(例如200表示请求成功)。
- 读取响应数据:逐行读取API返回的响应数据,将数据拼接成完整的响应内容。
- 输出响应内容:打印出API的响应结果,通常为JSON格式的K线数据。
- 异常处理:捕获并处理在请求和读取过程中可能发生的异常,输出错误信息以便调试。
使用WebSockets订阅天然气实时行情价格
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import javax.websocket.*;
// Special Note:
// GitHub: https://github.com/alltick/realtime-forex-crypto-stock-tick-finance-websocket-api
// Token Application: https://alltick.io
// Replace "testtoken" in the URL below with your own token
// API addresses for forex, cryptocurrencies, and precious metals:
// wss://quote.tradeswitcher.com/quote-b-ws-api
// Stock API address:
// wss://quote.tradeswitcher.com/quote-stock-b-ws-api
@ClientEndpoint
public class WebSocketJavaExample {
private Session session;
@OnOpen
public void onOpen(Session session) {
System.out.println("Connected to server");
this.session = session;
}
@OnMessage
public void onMessage(String message) {
System.out.println("Received message: " + message);
}
@OnClose
public void onClose(Session session, CloseReason closeReason) {
System.out.println("Disconnected from server");
}
@OnError
public void onError(Throwable throwable) {
System.err.println("Error: " + throwable.getMessage());
}
public void sendMessage(String message) throws Exception {
this.session.getBasicRemote().sendText(message);
}
public static void main(String[] args) throws Exception, URISyntaxException, DeploymentException, IOException {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
URI uri = new URI("wss://quote.tradeswitcher.com/quote-b-ws-api?token=testtoken"); // Replace with your actual token
WebSocketJavaExample client = new WebSocketJavaExample();
container.connectToServer(client, uri);
// Send subscription message for XNGUSD (Natural Gas)
client.sendMessage("{\"cmd_id\": 22002, \"seq_id\": 123,\"trace\":\"unique-trace-id\",\"data\":{\"symbol_list\":[{\"code\": \"XNGUSD\",\"depth_level\": 5}]}}");
// Wait for the client to be disconnected from the server (or until the user presses Enter)
System.in.read(); // Wait for user input before closing the program
}
}
这段代码的逻辑可以总结为以下步骤:
- 建立 WebSocket 连接:连接到指定的 WebSocket 服务器地址(API),用于获取实时市场数据。
- 处理连接事件:
- 连接成功 (
@OnOpen
):打印连接成功的消息并保存会话。 - 接收消息 (
@OnMessage
):接收并打印从服务器返回的消息(实时数据)。 - 连接关闭 (
@OnClose
):当连接断开时,打印断开连接的消息。 - 错误处理 (
@OnError
):处理在连接过程中可能发生的错误并输出错误信息。
- 连接成功 (
- 发送订阅消息:通过
sendMessage
方法发送一条包含查询天然气 ("XNGUSD") 数据的订阅消息。 - 保持连接:等待用户输入或服务器断开连接,以维持程序运行。
更多内容可查看这个Github地址:https://github.com/alltick/