【P000-003】交易費計算系統,從股票信息網絡接口獲取信息

找了一下,暫定用新浪的接口,現階段足夠了


接口爲:http://hq.sinajs.cn/list=標識股票代碼

標識爲sh滬市,sz深市,s_sh滬簡易信息,s_sz深簡易信息。


例如http://hq.sinajs.cn/list=sh600875


返回var hq_str_sh600875="東方電氣,12.48,-0.32,-2.50,135125,17091,........................";

以,分隔,需要的只有前面6個:

0     股票名

1    今日開盤價;

2    昨日收盤價;

3    當前價格;

4    今日最高價;

5    今日最低價


傳回的值整個轉成String,再使用public String[] split(String regex)方法分割,split()方法簡單說就是根據regex來分割比如"DF,GG+HH"按",'"就分割成"DF" 和 "GG+HH"。

簡單寫了個提取的代碼


package test;
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.InputStream;
public class AccessNI {
    final String NULLRES = "無返回值!";
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        final AccessNI ani = new AccessNI();
        new Thread() {
            public void run() {
                String result = ani.accessByGet();
                ani.splitString(result);
            }
        }.start();
    }
    public void splitString(String result) {
        if (!result.equals(NULLRES)) {
            String[] a = new String[6];
            String[] var = result.split("=\"");
            String s = var[1];
            String[] as = s.split(",");
            for (int i = 0; i < a.length; i++) {
                a[i] = as[i];
                System.out.println(a[i]);
            }
        }
    }
    public String accessByGet() {
        // 提交至服務器
        // 拼裝路徑
        try {
            String path = "http://hq.sinajs.cn/list=sh600875";
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("GET");
            // 取得返回的狀態碼
            int code = conn.getResponseCode();
            if (code == 200) {
                // 請求成功
                InputStream is = conn.getInputStream();
                String text = StreamTools.readInputStream(is);
                return text;
            } else {
                return NULLRES;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return NULLRES;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章