sina获取实时股票数据
- - 互联网 - ITeye博客* 从请求的URL中获取返回的数据流. // setConnectTimeout:设置连接主机超时(单位:毫秒). // setReadTimeout:设置从主机读取数据超时(单位:毫秒). // 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在 http正文内,因此需要设为true,.
package com.cmn; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.regex.Pattern; import net.sf.json.JSONObject; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; public class StockUtil { public static final int CONNECTTIMEOUT = 5000; public static final int READRESPONSETIMEOUT = 5000; public static final String UTF8 = "UTF-8"; public static final String GBK = "GBK"; public static boolean isNotBlank(Object b) { if (b == null) { return false; } String a = b.toString(); if (a.equals("")) { return false; } else { return true; } } public static boolean isBlank(Object b) { if (b == null) { return true; } String a = b.toString(); if (a.equals("")) { return true; } else { return false; } } public static boolean isTrue(Object b) { if (b == null) { return false; } String a = b.toString(); if (a.equals("1") || a.equals("true")) { return true; } return false; } // regular pattern public static boolean regex(String str, String regex) { if (str == null) { return false; } Pattern pattern = Pattern.compile(regex); return pattern.matcher(str).matches(); } public static String postUrl(String queryUrl, Map data) { Iterator e = data.keySet().iterator(); StringBuffer a = new StringBuffer(); while (e.hasNext()) { String key = (String) e.next(); a.append(key).append("=").append(data.get(key)).append("&"); } InputStream ips = getInputPostStream(queryUrl, a.toString()); if (ips == null) { System.err.println("connect error, please check your connection!"); return null; } String response = getResponse(ips, "utf-8"); if (response == null) { System.err.println("connect error, please check your connection."); return null; } else { // System.out.println(response); } return response; } /** * 从请求的URL中获取返回的数据流 * * @param requestUrl * @return InputStream */ public static InputStream getInputStream(String requestUrl) { URL url = null; HttpURLConnection conn = null; InputStream in = null; try { url = new URL(requestUrl); conn = (HttpURLConnection) url.openConnection(); // System.setProperty("sun.net.client.defaultConnectTimeout", // 超时毫秒数字符串); // System.setProperty("sun.net.client.defaultReadTimeout", // 超时毫秒数字符串); // setConnectTimeout:设置连接主机超时(单位:毫秒) conn.setConnectTimeout(5000); // setReadTimeout:设置从主机读取数据超时(单位:毫秒) conn.setReadTimeout(5000); // 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在 http正文内,因此需要设为true, // 默认情况下是false; conn.setDoOutput(true); // 设置是否从httpUrlConnection读入,默认情况下是true; conn.setDoInput(true); conn.setUseCaches(true); conn.setRequestMethod("GET"); conn.connect(); // 实际发送请求的代码段就在这里 in = conn.getInputStream(); } catch (IOException e) { e.printStackTrace(); return null; } finally { conn = null; url = null; } return in; } /** * @description 从请求的URL中获取返回的数据 * @param requestUrl * @param postParam * @return */ public static InputStream getInputPostStream(String requestUrl, String postParam) { URL url = null; HttpURLConnection conn = null; InputStream in = null; try { url = new URL(requestUrl); URLConnection urlConn = url.openConnection(); conn = (HttpURLConnection) urlConn; // setConnectTimeout:设置连接主机超时(单位:毫秒) conn.setConnectTimeout(30000); // setReadTimeout:设置从主机读取数据超时(单位:毫秒) conn.setReadTimeout(30000); // 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在 http正文内,因此需要设为true, // 默认情况下是false; conn.setDoOutput(true); // 设置是否从httpUrlConnection读入,默认情况下是true; conn.getDoInput(); // Post 请求不能使用缓存 conn.setUseCaches(false); conn.setRequestMethod("POST"); // 此处getOutputStream会隐含的进行connect(即:如同调用上面的connect()方法, // 所以在开发中不调用上述的connect()也可以)。 OutputStream outStrm = conn.getOutputStream(); // 向对象输出流写出数据,这些数据将存到内存缓冲区中 outStrm.write(postParam.getBytes()); // 刷新对象输出流,将任何字节都写入潜在的流中(些处为ObjectOutputStream) outStrm.flush(); // 关闭流对象。此时,不能再向对象输出流写入任何数据,先前写入的数据存在于内存缓冲区中, // 在调用下边的getInputStream()函数时才把准备好的http请求正式发送到服务器 outStrm.close(); // 实际发送请求的代码段就在这里 in = conn.getInputStream(); } catch (IOException e) { e.printStackTrace(); return null; } finally { conn = null; url = null; } return in; } /** * @description 将流数据转换成字符串 * @param ips * @param codeFormat * @return */ public static String getResponse(InputStream ips, String codeFormat) { StringBuffer sb = new StringBuffer(); InputStreamReader isreader = null; try { isreader = new InputStreamReader(ips, codeFormat); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } BufferedReader bufferedReader = new BufferedReader(isreader); String line = null; try { while ((line = bufferedReader.readLine()) != null) { sb.append(line); } bufferedReader.close(); isreader.close(); ips.close(); ips = null; } catch (IOException e) { e.printStackTrace(); return null; } return sb.toString(); } /** * 根据url调用web接口 * * @param url * 访问地址, 必备参数 * @param method * 请求方式post还是get, 默认get * @param params * 参数列表 post必备, 比如:"name=张三&age=18" * @param sessionInfo * 可以保持session, 默认不保持 * @param encoding * 编码格式, 默认UTF_8 * @param isLine * 得到的源码是否换行, 默认false * @return String */ public static String requestUrl(String url, String method, String params, String sessionInfo, String encoding, boolean isLine) { try { encoding = (isBlank(encoding) ? UTF8 : encoding); method = (isBlank(method) ? "GET" : method.toUpperCase()); String mathStr = "mathRandom=" + Math.random(); if (method.equals("GET")) { url += (url.indexOf("?") != -1 ? "&" : "?") + mathStr; if (!isBlank(params)) { url += "&" + params; } System.out.println("url="+url); } HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); if (!isBlank(sessionInfo)) { connection.setRequestProperty("Cookie", sessionInfo); } connection.setRequestMethod(method); connection.setConnectTimeout(15000); connection.setReadTimeout(15000); if (method.equals("POST")) { connection.setDoOutput(true); params = (isBlank(params) ? mathStr : params + "&" + mathStr); OutputStream output = connection.getOutputStream(); output.write(params.getBytes(encoding)); output.flush(); output.close(); } // String result = FileUtil.readFile(connection.getInputStream(), // encoding, 1, isLine); String result = getResponse(connection.getInputStream(), encoding); connection.disconnect(); return result; } catch (Exception e) { System.out.println("根据url调用web接口" + e); e.printStackTrace(); } return null; } public static void main(String[] args) { Date date = new Date(); System.out.println(requestUrl("http://hq.sinajs.cn/list=sh601002 ", "GET", null, null, "GBK", false)); System.out.println("本次调用web接口耗时" + (new Date().getTime() - date.getTime()) + "毫秒"); } }