使用Java代码进行sina股票接口调用
时间: 2023-09-16 21:13:41 浏览: 55
好的,下面是使用Java代码调用新浪股票接口的示例:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class StockAPI {
/**
* 调用新浪股票接口获取股票信息
* @param code 股票代码,例如:sh600519
* @return 返回股票信息
*/
public static String getStockInfo(String code) {
String result = "";
try {
// 构建URL
String urlStr = "http://hq.sinajs.cn/list=" + code;
URL url = new URL(urlStr);
// 打开连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置请求方式
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
// 获取输入流
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "GBK"));
// 读取数据
String line;
while ((line = in.readLine()) != null) {
result += line;
}
// 关闭连接
in.close();
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static void main(String[] args) {
// 调用getStockInfo方法获取股票信息
String stockInfo = getStockInfo("sh600519");
System.out.println(stockInfo);
}
}
```
在上面的示例中,我们使用了Java中的HttpURLConnection类来构建URL请求,调用新浪股票接口获取股票信息。在调用接口时,需要将股票代码作为参数传入,例如:sh600519表示查询贵州茅台的股票信息。在main方法中,我们将查询的结果打印出来。
希望以上内容能够帮助到您!