这是我使用crumbs下载历史雅虎财务报价的Java代码。对不起,这不是最有效的代码。我还在学习Java。对我来说一切看起来都是正确的,但是在拿起面包屑并尝试第二次访问“https”// query1.finance.yahoo.com之后我得到错误401 ...“
我做错了什么想法?
URL myUrl = null;
try {
myUrl = new URL("https://finance.yahoo.com");
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
URLConnection urlConn = null;
try {
urlConn = myUrl.openConnection();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
urlConn.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String headerName=null;
String crumb = null;
for (int i = 1; (headerName = urlConn.getHeaderFieldKey(i)) != null; i++) {
if (headerName.equals("Set-Cookie")) {
String cookie = urlConn.getHeaderField(i);
cookie = cookie.substring(0, cookie.indexOf(";"));
crumb = cookie.substring(cookie.indexOf("=") + 1, cookie.indexOf("&"));
}
}
StringBuilder qUrl = new StringBuilder();
qUrl.append("https://query1.finance.yahoo.com/v7/finance/download/AAPL");
qUrl.append("?period1=" + 1495813803L);
qUrl.append("&period2=" + 1497887408L);
qUrl.append("&interval=1d");
qUrl.append("&events=history");
qUrl.append("&crumb=" + crumb);
URL url = null;
try {
url = new URL(qUrl.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection conn;
InputStream is = null;
try {
conn = url.openConnection();
String redirect = conn.getHeaderField("Location"); // Can handle one redirection
if(redirect != null ) {
conn = new URL(redirect).openConnection();
}
is = conn.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}