1. 程式人生 > >新浪股票介面獲取歷史資料

新浪股票介面獲取歷史資料

這兩天做了一個呼叫新浪股票介面獲取實時以及歷史股票資料的應用,因為新浪沒有公開關於其介面的官方文件,所以通過各種百度差了很多關於新浪股票介面的使用,不過大家基本都是轉載或者直接複製,對於實時資料的獲取講的很詳細,但是缺少獲取歷史資料的方法。關於實時資料的獲取大家可以看這篇部落格:實時股票資料介面 獲取的資料是類似下面的json陣列:日期、開盤價、最高價、最低價、收盤價、成交量:獲取的資料會有很多,然後根據自己需要進行解析,我需要的是每天的收盤價,股市是每個工作日下午3點收盤,所以我只需要找到每天的下午三點時刻的資料進行過濾即可:1、新建一個歷史資料物件類:
public class HistoryModel {
    public String day;
    public String close;
    public HistoryModel(String day, String close) {
        this.day = day;
        this
.close = close; } }
2、新建一個股票多次歷史資料類:和上一個區別就是,這裡包含的是所有的歷史資料:引數包括股票名字、程式碼、現在的價格、歷史資料:
public class HistoryModels {
    public String name;
    public String code;
    public String now;
    public List<HistoryModel> list;
    public HistoryModels(String name, String code, String now, List<HistoryModel> list) {
        this
.name = name; this.code = code; this.now = now; this.list = list; } }

3、將需要查詢的股票的程式碼帶進url裡通過HTTP請求json資料,我這裡用的Volley請求的:

其中將時間點未15:00:00的資料過濾出來,組合乘List之後在全部賦值組合成一個HistoryModels存放股票資訊以及股票的所有歷史資料。
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(Home.context);
String url1 = "http://money.finance.sina.com.cn/quotes_service/api/json_v2.php/CN_MarketData.getKLineData?symbol=" + Home.myChoiceModelList.get(ii).code + "&scale=60&ma=no&datalen=1023"; // Request a string response from the provided URL. StringRequest stringRequest1 = new StringRequest(Request.Method.GET, url1, new Response.Listener<String>() { @Override public void onResponse(String response) { List<HistoryModel> historyList = Convert(response,new TypeToken<List<HistoryModel>>() { }.getType()); List<HistoryModel> historyList2 = new ArrayList<>(); if(historyList!=null) { for (int j = 0; j < historyList.size(); j++) { if (historyList.get(j).day.split(" ")[1].equals("15:00:00")) { historyList2.add(historyList.get(j)); } } } HistoryModels model = new HistoryModels(Home.myChoiceModelList.get(ii).name, Home.myChoiceModelList.get(ii).code, Home.myChoiceModelList.get(ii).now, historyList2); cllList.add(model); Message msg = new Message(); msg.what = 0x002; handler.sendMessage(msg); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }); queue.add(stringRequest1);
4、其中對json資料的處理,即從json轉化成資料物件的方法如下:
/*
* Json轉換泛型 */
public static <T> T Convert(String jsonString, Type cls) {
    T t = null;
    try {
        if (jsonString != null && !jsonString.equals("")) {
            Gson gson = new Gson();
t = gson.fromJson(jsonString, cls);
}
    } catch (Exception e) {
        e.printStackTrace();
}
    return t;
}
關於股票的實時資料這裡沒有描述,通過文章開頭連線的部落格可以瞭解到,寫的很詳細。