我正在运行下面的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相关问答推荐

Maven Google Sheets版本问题

更新我们的一个文物后出现了严重的符号引用错误

如何为具有多对多关系的实体的给定SQL查询构建JPA规范?

具有额外列的Hibert多对多关系在添加关系时返回NonUniqueHealthExcellent

我的scala文件失败了Scala.g4 ANTLR语法

XPages-在第二次点击按钮之前延迟

现场观看Android Studio中的变化

为什么JAVA&S清洁器使用链表而不是并发HashSet?

第二次按下按钮后,我需要将按钮恢复到其原始状态,以便它可以再次工作

对于亚洲/香港,使用ResolverStyle.STRICT的LocalDate.parse返回意外结果

通过Spring Security公开Spring Boot执行器端点

MimeMessage emlMessage=new MimeMessage(Session,emlInputStream);抛出InvocationTargetException

如何在 spring 数据的MongoDB派生查询方法中使用$EXISTS

无法使用Freemarker从XML中读取重复的标记值

通过Java列表中的某些字段搜索值

无法使用Java PreparedStatement在SQLite中的日期之间获取结果

在一行中检索字符分隔字符串的第n个值

将BlockingQueue+守护程序线程替换为执行器

活泼的一次判断成语,结果中等

在Java中比较同一多维数组的两个不同的字符串元素