项目上传到GitHub上啦https://github.com/SONGSONG729/stock
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>stock</title>
<script src="jquery-3.3.1.js"></script>
<script src="echarts.js"></script>
</head>
<body>
<div>
<form action="" method="post">
<input type="text" id="gid">
<button type="button" id="search">search</button>
</form>
</div>
<div style="height: 50px;"></div>
<!-- 为ECharts准备一个具备大小(宽高)的Dom -->
<div id="main" style="width: 90%;height:300px; text-align: center"></div>
</body>
<script>
$(function () {
var timeVal;
var nowPriVal;
var buyOnePriVal;
var buyTwoPriVal;
var sellOnePriVal;
var sellTwoPriVal;
var myChart = echarts.init(document.getElementById('main'));
var timeData = [];
var nowPriData = [];
var buyOnePriData = [];
var buyTwoPriData = [];
var sellOnePriData = [];
var sellTwoPriData = [];
function getStockData() {
var gid = $('#gid').val();
$.ajax({
type: "post",
url: "getData",
dataType: 'json',
data: {
gid: gid
},
success: function (res) {
console.log(res);
// 接收聚合股票api传回来的json数据
// nowPriVal = res.result[0].data.nowPri;
// buyOnePriVal = res.result[0].data.buyOnePri;
// buyTwoPriVal = res.result[0].data.buyTwoPri;
// sellOnePriVal = res.result[0].data.sellOnePri;
// sellTwoPriVal = res.result[0].data.sellTwoPriPri;
// timeVal = res.result[0].data.time;
// 接收新浪股票api传回来的json数据
nowPriVal = res.nowPri;
buyOnePriVal = res.buyOnePri;
buyTwoPriVal = res.buyTwoPri;
sellOnePriVal = res.sellOnePri;
sellTwoPriVal = res.sellTwoPriPri;
timeVal = res.time;
nowPriData.push(nowPriVal);
buyOnePriData.push(buyOnePriVal);
buyTwoPriData.push(buyTwoPriVal);
sellOnePriData.push(sellOnePriVal);
sellTwoPriData.push(sellTwoPriVal);
timeData.push(timeVal);
myChart.setOption({
title: {
text: '股票实时价格'
},
tooltip: {
trigger: 'axis',
},
legend: {
type: 'scroll',
data: ['当前价格', '', '买一报价', '买二报价', '卖一报价', '卖二报价']
},
xAxis:{
data:timeData
},
yAxis:{},
series: [
{
name: '当前价格',
type:'line',
data: nowPriData
},
{
name: '买一报价',
type:'line',
data: buyOnePriData
},
{
name: '买二报价',
type:'line',
data: buyTwoPriData
},
{
name: '卖一报价',
type:'line',
data: sellOnePriData
},
{
name: '卖二报价',
type:'line',
data: sellTwoPriData
}
]
});
}
});
}
$('#search').click(function(){
getStockData();
var sh;
sh = setInterval(function () {
getStockData();
}, 5*1000);
setTimeout(function () {
clearInterval(sh);
},20*5*1000);
});
})
</script>
</html>
package com.song.controler;
import net.sf.json.JSONObject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
@WebServlet("/getData")
public class StockRequestServlet extends HttpServlet {
StockRequest request = new StockRequest();
StockSN StockSN = new StockSN();
JSONObject object = null;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String gid = req.getParameter("gid");
System.out.println("gid="+gid);
// object = request.getRequest1(gid); // 用聚合数据股票api
object = StockSN.request(gid); // 用新浪股票api
System.out.println(object);
resp.setCharacterEncoding("utf-8");
resp.setContentType("application/json; charset=utf-8");//返回的格式必须设置为application/json
PrintWriter out = resp.getWriter();
out.print(object); //写入到返回结果中
//完成,执行到这里就会返回数据给前端,前端结果为success,调用success里面的内容
}
}
package com.song.controler;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONObject;
/**
*股票数据调用示例代码 - 聚合数据
*在线接口文档:http://www.juhe.cn/docs/21
**/
public class StockRequest {
public static final String DEF_CHATSET = "UTF-8";
public static final int DEF_CONN_TIMEOUT = 30000;
public static final int DEF_READ_TIMEOUT = 30000;
public static String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
//配置您申请的KEY
public static final String APPKEY ="d55b1a099e7c0cc5f9db45fc9357530a";
//1.沪深股市
public static JSONObject getRequest1(String gid){
String result =null;
JSONObject object = null;
String url ="http://web.juhe.cn:8080/finance/stock/hs";//请求接口地址
Map params = new HashMap();//请求参数
params.put("gid",gid);//股票编号,上海股市以sh开头,深圳股市以sz开头如:sh601009
params.put("key",APPKEY);//APP Key
try {
result =net(url, params, "GET");
object = JSONObject.fromObject(result);
if(object.getInt("error_code")==0){
return object;
}else{
return object;
}
} catch (Exception e) {
e.printStackTrace();
return object;
}
}
/**
*
* @param strUrl 请求地址
* @param params 请求参数
* @param method 请求方法
* @return 网络请求字符串
* @throws Exception
*/
public static String net(String strUrl, Map params,String method) throws Exception {
HttpURLConnection conn = null;
BufferedReader reader = null;
String rs = null;
try {
StringBuffer sb = new StringBuffer();
if(method==null || method.equals("GET")){
strUrl = strUrl+"?"+urlencode(params);
}
URL url = new URL(strUrl);
conn = (HttpURLConnection) url.openConnection();
if(method==null || method.equals("GET")){
conn.setRequestMethod("GET");
}else{
conn.setRequestMethod("POST");
conn.setDoOutput(true);
}
conn.setRequestProperty("User-agent", userAgent);
conn.setUseCaches(false);
conn.setConnectTimeout(DEF_CONN_TIMEOUT);
conn.setReadTimeout(DEF_READ_TIMEOUT);
conn.setInstanceFollowRedirects(false);
conn.connect();
if (params!= null && method.equals("POST")) {
try {
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(urlencode(params));
} catch (Exception e) {
// TODO: handle exception
}
}
InputStream is = conn.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sb.append(strRead);
}
rs = sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
reader.close();
}
if (conn != null) {
conn.disconnect();
}
}
return rs;
}
//将map型转为请求参数型
public static String urlencode(Map<String,Object>data) {
StringBuilder sb = new StringBuilder();
for (Map.Entry i : data.entrySet()) {
try {
sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
var hq_str_sz002649="博彦科技,9.120,9.200,9.290,9.290,9.060,9.290,9.300,8038755,73904694.700,15000,9.290,51300,9.280,47151,9.270,36000,9.260,26100,9.250,115500,9.300,32300,9.310,26600,9.320,68000,9.330,22300,9.340,2020-04-22,15:00:03,00";
可以通过逗号分割字符串,再将的数据存入map中,再转换成json格式的数据。
{"buyTwoPri":"9.280","sellTwoPri":"9.310","nowPri":"9.290","sellOnePri":"9.300","time":"15:00:03","buyOnePri":"9.290"}
package com.song.controler;
import net.sf.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
public class StockSN {
public static JSONObject request(String code) {
JSONObject result = null;
try {
String url = "http://hq.sinajs.cn/list=" + code;
URL ur = new URL(url);
HttpURLConnection uc = (HttpURLConnection) ur.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(ur.openStream(), "GBK"));
String line;
while ((line = reader.readLine()) != null) {
System.out.print(line);
String [] arrayStr=line.split(",");
// for (String s: arrayStr){
// System.out.print(s+" ");
// }
// System.out.println();
Map<String,String> map = new HashMap<>();
map.put("nowPri",arrayStr[3]);
map.put("buyOnePri",arrayStr[11]);
map.put("buyTwoPri",arrayStr[13]);
map.put("sellOnePri",arrayStr[21]);
map.put("sellTwoPri",arrayStr[23]);
map.put("time",arrayStr[31]);
System.out.println(map);
result = JSONObject.fromObject(map);
System.out.println(result);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}