我想从 NSE(印度国家证券交易所)获取数据。 NSE 提供 API 来获取数据。例如
https://www.nseindia.com/api/option-chain-indices?symbol=BANKNIFTY
但是如果我转到上面的 URL,那么我什么也看不到,它会显示消息“Resource not found”。
所以这里的解决方法是 - 我需要访问网站 - https://www.nseindia.com/ 一次,然后如果我调用以前的 URL,它会返回数据。
这是因为,它需要来自
https://www.nseindia.com/. 的响应的
set-cookie
标头
我可以使用
Node JS
在Axios
中管理它,下面是它的代码片段
saveOptionChainFile() {
return axios.default
.get("https://www.nseindia.com/")
.then((res) => {
return axios.default.get('https://www.nseindia.com/api/option-chain-indices?symbol=BANKNIFTY', {
headers: {
cookie: res.headers['set-cookie'].join(';')
}
})
})
.then(res => {
let data = JSON.stringify(res.data)
fs.writeFileSync('../files/option-chain-indices.json', data);
})
.catch((err) => {
console.log(err);
});
}
但同样我想在
C#
中尝试使用HttpClient
我为初始请求尝试了这个简单的代码
try
{
using (var client = new HttpClient())
{
using HttpResponseMessage response = await client.GetAsync("https://www.nseindia.com/");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", e.Message);
}
我得到如下异常。
System.Threading.Tasks.TaskCanceledException: 'The request was canceled due to the configured HttpClient.Timeout of 100 seconds elapsing.'
另外我不确定如何将
set-cookie
标头传递给另一个请求。有什么想法吗?
要将 set-cookie 标头传递给另一个请求,您可以将其从初始请求的响应标头中提取出来,并将其添加到后续请求的标头中。
try
{
// Create HttpClient with longer timeout
using (var client = new HttpClient())
{
client.Timeout = TimeSpan.FromSeconds(300);
// Make initial request to get set-cookie header
using HttpResponseMessage response = await client.GetAsync("https://www.nseindia.com/");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
// Get set-cookie header
string setCookieHeader = response.Headers.GetValues("set-cookie").FirstOrDefault();
// Make subsequent request with set-cookie header
using HttpResponseMessage response2 = await client.GetAsync("https://www.nseindia.com/api/option-chain-indices?symbol=BANKNIFTY",
new System.Net.Http.Headers.AuthenticationHeaderValue("cookie", setCookieHeader));
response2.EnsureSuccessStatusCode();
string responseBody2 = await response2.Content.ReadAsStringAsync();
Console.WriteLine(responseBody2);
}
}
catch (HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", e.Message);
}