我正在运行下面的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);
        }
    }
}

推荐答案

您在呼叫导致401的"https://www.nseindia.com/api/option-chain-indices?symbol=MIDCPNIFTY"时添加了多个Cookie请求属性.

此外,我更新了您的代码,修复了您在执行请求时在头文件中添加Cookie的方式.

现在,这将会起作用:)

试试这个:

import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.*;
import java.util.List;
import java.io.InputStream;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

public class PollNSEIndia {
    public static void main(String args[]) throws Exception {
        while (true) {
            CookieManager cookieManager = new CookieManager();
            CookieHandler.setDefault(cookieManager);
            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");
            baseUrlConnection.getContent();
            List<HttpCookie> cookieList = cookieManager.getCookieStore().getCookies();

            URL url = new URL("https://www.nseindia.com/api/option-chain-indices?symbol=MIDCPNIFTY");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setRequestProperty("Cookie", cookieList.stream().filter(Objects::nonNull)
                    .map(cookie -> cookie.getName() + "=" + cookie.getValue()).collect(Collectors.joining(";")));
            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(httpURLConnection.getResponseCode());
            System.out.println("Got inputstream.");

            // checking output via Jackson for testing (ignore this)
            ObjectMapper mapper = new ObjectMapper();
            Map data = mapper.readValue(inputStream, Map.class);
            System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(data));

            Thread.sleep(1000);
        }
    }
}

输出:

200
Got inputstream.
{
  "records" : {
    "expiryDates" : [ "09-Oct-2023", "16-Oct-2023", "23-Oct-2023", "30-Oct-2023", "06-Nov-2023", "22-Dec-2023" ],
    "data" : [ {
      "strikePrice" : 7800,
      "expiryDate" : "09-Oct-2023",
      "PE" : {
        "strikePrice" : 7800,
        "expiryDate" : "09-Oct-2023",
        "underlying" : "MIDCPNIFTY",
        "identifier" : "OPTIDXMIDCPNIFTY09-10-2023PE7800.00",
        "openInterest" : 386,
        "changeinOpenInterest" : -33,
        "pchangeinOpenInterest" : -7.875894988066825,
        "totalTradedVolume" : 985,
        "impliedVolatility" : 52.73,
        "lastPrice" : 0.05,
        "change" : -0.4,
....

Java相关问答推荐

方法没有用正确的值填充数组—而是将数组保留为null,'

基本时态运算的ISO-8601周数据表示法

Spring Boot 3.2.2中的@Inject和@Resource Remove

为什么S的文档中说常量方法句柄不能在类的常量池中表示?

由于 list 中的权限错误,Android未生成

Spring和可编辑";where";@Query

Java-动态绑定-问题-了解

使用Jolt将字段转换为列表

带有Health Check的Spring Boot BuildPack打破了本机映像构建过程

有效的公式或值列表必须少于或等于255个字符

Lombok@Nonnull是否也对供应商有影响?

在处理2个映射表时,没有更多的数据可从套接字读取

FETCH类型设置为LAZY,但它仍会发送第二个请求

Win32函数的JNA绑定DwmGetColorizationColor返回E_INVALIDARG错误

未调用OnBackPressedCallback-Activitiy立即终止

如何在Struts2中使用操作类中的结果注释重定向到不同的命名空间

我无法在我的Spring Boot应用程序中导入CSV依赖项

如何使用带有可选参数的类生成器?

java.lang.ClassCastException:com.google.firebase.FirebaseException无法转换为com.google.fire base.auth.FirebaseAuthException

javax.crypto-密码对象-提供者服务是如何工作的?