新版eoLinkerAPIShop股票行情数据API接口Java调用示例代码docWord格式.docx
《新版eoLinkerAPIShop股票行情数据API接口Java调用示例代码docWord格式.docx》由会员分享,可在线阅读,更多相关《新版eoLinkerAPIShop股票行情数据API接口Java调用示例代码docWord格式.docx(53页珍藏版)》请在冰豆网上搜索。
packagenet.apishop.www.controller;
importjava.io.DataOutputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.UnsupportedEncodingException;
import.HttpURLConnection;
import.MalformedURLException;
import.URL;
import.URLEncoder;
importjava.util.HashMap;
importjava.util.Map;
importcom.alibaba.fastjson.JSONObject;
/**
*httpUrlConnection访问远程接口工具
*/
publicclassApi
{
/**
*方法体说明:
向远程接口发起请求,返回字节流类型结果
*paramurl接口地址
*paramrequestMethod请求方式
*paramparams传递参数重点:
参数值需要用Base64进行转码
*returnInputStream返回结果
publicstaticInputStreamhttpRequestToStream(Stringurl,StringrequestMethod,Map<
String,String>
params)
{
InputStreamis=null;
try
Stringparameters="
"
;
booleanhasParams=false;
//将参数集合拼接成特定格式,如name=zhangsan&
age=24
for(Stringkey:
params.keySet())
Stringvalue=URLEncoder.encode(params.get(key),"
UTF-8"
);
parameters+=key+"
="
+value+"
&
hasParams=true;
}
if(hasParams)
parameters=parameters.substring(0,parameters.length()-1);
//请求方式是否为get
booleanisGet="
get"
.equalsIgnoreCase(requestMethod);
//请求方式是否为post
booleanisPost="
post"
if(isGet)
url+="
?
+parameters;
URLu=newURL(url);
HttpURLConnectionconn=(HttpURLConnection)u.openConnection();
//请求的参数类型(使用restlet框架时,为了兼容框架,必须设置Content-Type为“”空)
conn.setRequestProperty("
Content-Type"
"
application/octet-stream"
//conn.setRequestProperty("
application/x-www-form-urlencoded"
//设置连接超时时间
conn.setConnectTimeout(50000);
//设置读取返回内容超时时间
conn.setReadTimeout(50000);
//设置向HttpURLConnection对象中输出,因为post方式将请求参数放在http正文内,因此需要设置为ture,默认false
if(isPost)
conn.setDoOutput(true);
//设置从HttpURLConnection对象读入,默认为true
conn.setDoInput(true);
//设置是否使用缓存,post方式不能使用缓存
conn.setUseCaches(false);
//设置请求方式,默认为GET
conn.setRequestMethod(requestMethod);
//post方式需要将传递的参数输出到conn对象中
DataOutputStreamdos=newDataOutputStream(conn.getOutputStream());
dos.writeBytes(parameters);
dos.flush();
dos.close();
//从HttpURLConnection对象中读取响应的消息
//执行该语句时才正式发起请求
is=conn.getInputStream();
catch(UnsupportedEncodingExceptione)
e.printStackTrace();
catch(MalformedURLExceptione)
catch(IOExceptione)
returnis;
publicstaticvoidmain(Stringargs[])
Stringurl="
StringrequestMethod="
POST"
Map<
params=newHashMap<
();
params.put("
apiKey"
"
your_api_key"
//需要从获取
stock_code"
//股票代码
period"
//1:
1分钟2:
5分钟3:
15分钟4:
30分钟5:
60分钟6:
日k线7:
周k线8:
月k线
request_num"
//请求行数
position_str"
//定位串,默认-1从头开始
Stringresult=null;
InputStreamis=httpRequestToStream(url,requestMethod,params);
byte[]b=newbyte[is.available()];
is.read(b);
result=newString(b);
if(result!
=null)
JSONObjectjsonObject=JSONObject.parseObject(result);
Stringstatus_code=jsonObject.getString("
statusCode"
if(status_code=="
000000"
)
//状态码为000000,说明请求成功
System.out.println("
请求成功:
+jsonObject.getString("
result"
));
else
//状态码非000000,说明请求失败
请求失败:
desc"
//返回内容异常,发送请求失败,以下可根据业务逻辑自行修改
发送请求失败"
}
2.实时行情查询
3.查询股票列表
catch(MalformedURLExc