package cn.uway.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
*
* 实时查询股票情况
*
* @author Administrator
*
*/
public class StockQuery
{
private String requestUrl = "http://qt.gtimg.cn/r=0.7938921226847172q=";
private long sleepSecond = 30;
private List<String> stockCodeList;
private SimpleDateFormat dateFormate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public StockQuery(List<String> stockCodeList,long sleepSecond)
{
this.stockCodeList = stockCodeList;
this.sleepSecond = sleepSecond;
}
public void executeQuery() throws IOException, InterruptedException
{
String request = getRequestData();
while (true)
{
System.out.println(dateFormate.format(new Date()));
System.out.println("***********************************************************************");
sendRequest(request);
Thread.sleep(sleepSecond * 1000);
}
}
private String getRequestData()
{
StringBuilder requestUrlWithPara = new StringBuilder(requestUrl);
for(String code : stockCodeList)
{
requestUrlWithPara.append(code+",");
}
if(stockCodeList.size() > 0)
{
requestUrlWithPara.deleteCharAt(requestUrlWithPara.length()-1);
}
return requestUrlWithPara.toString();
}
private void sendRequest(String request) throws IOException
{
URL url = new URL(request);
URLConnection conn = url.openConnection();
InputStream in = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in,"GBK"));
String tmp = null;
while (null != (tmp = br.readLine()))
{
tmp = tmp.replace('~', '\t');
int index = tmp.indexOf('=');
tmp = tmp.substring(index + 2);
int headerIndex = tmp.indexOf("\t");
tmp = tmp.substring(headerIndex+1);
int last = tmp.lastIndexOf(";");
tmp = tmp.substring(0, last-1);
System.out.println(tmp);
}
br.close();
in.close();
}
public static void main(String[] args)
{
//股票代号列表
List<String> codeList = new ArrayList<String>();
codeList.add("s_sh601377");
codeList.add("s_sh600828");
codeList.add("s_sz002008");
codeList.add("s_sz000157");
codeList.add("s_sh000001");
StockQuery stockQuery = new StockQuery(codeList, 30);
try
{
stockQuery.executeQuery();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}