我正在运行下面的Java代码,用于从NSE证券交易所的REST API获取选项链数据.首先,我访问主页,并使用后续请求中响应的cookie来实际获取选项链数据.我不断地重复这两个步骤,完成一项预定的任务.它工作了一两次,但在那之后,它开始在HTTP响应中给出401个未经授权的错误.我在两个请求头中都设置了浏览器名称.任何帮助都是非常感激的.
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.io.InputStream;
public class PollNSEIndia {
public static void main(String args[]) throws Exception {
while (true) {
HttpURLConnection baseUrlConnection = (HttpURLConnection) new URL("https://www.nseindia.com/").openConnection();
baseUrlConnection.setRequestProperty("Connection", "keep-alive");
baseUrlConnection.setRequestProperty("Cache-Control", "max-age=0");
baseUrlConnection.setRequestProperty("Upgrade-Insecure-Requests", "1");
baseUrlConnection.setRequestProperty(
"User-Agent",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)"
+ " Chrome/89.0.4389.114 Safari/537.36");
baseUrlConnection.setRequestProperty(
"Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
baseUrlConnection.setRequestProperty("Accept-Language", "en-US,en;q=0.9");
List<String> cookies = baseUrlConnection.getHeaderFields().get("Set-Cookie");
URL url = new URL("https://www.nseindia.com/api/option-chain-indices?symbol=MIDCPNIFTY");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
for (String cookie : cookies) {
httpURLConnection.addRequestProperty("Cookie", cookie.split(";", 2)[0]);
}
httpURLConnection.setRequestProperty("Connection", "keep-alive");
httpURLConnection.setRequestProperty("Cache-Control", "max-age=0");
httpURLConnection.setRequestProperty("Upgrade-Insecure-Requests", "1");
httpURLConnection.setRequestProperty(
"User-Agent",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)"
+ " Chrome/89.0.4389.114 Safari/537.36");
httpURLConnection.setRequestProperty(
"Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
httpURLConnection.setRequestProperty("Accept-Language", "en-US,en;q=0.9");
InputStream inputStream = httpURLConnection.getInputStream();
System.out.println("Got inputstream.");
Thread.sleep(1000);
}
}
}