I have written this HTTPS Client code to get data from NSE Server.
On button click, the code is expected to send a request to the Server and get data in return.
Half the times when I click the button I don’t get data from the Server, and it returns me Status Code 401 – Unauthorized. But other half of the times when I click the button, the server returns me the required data and a Status Code 200.
I am sending a GET Request to the Server
This is my Code,
private void Button_Click(object sender, RoutedEventArgs e)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls13;
string baseUrl = "https://www.nseindia.com/api/reports?archives=";
string encodedurl = "[{"name":"Full Bhavcopy and Security Deliverable data","type":"daily-reports","category":"capital-market","section":"equities"}]";
string endurl = "&date=31-Jul-2024&type=equities&mode=single";
string url = baseUrl + Uri.EscapeDataString(encodedurl)+endurl;
GetRequest(url);
}
async static void GetRequest(string url)
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Accept", "*/*");
client.DefaultRequestHeaders.Add("Referer", "https://www.nseindia.com/all-reports");
client.DefaultRequestHeaders.Add("sec-ch-ua", ""Not)A;Brand";v="99", "Brave";v="127", "Chromium";v="127"");
client.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36");
client.DefaultRequestHeaders.Add("x-requested-with", "XMLHttpRequest");
client.DefaultRequestHeaders.Add("Dnt", "1");
using (HttpResponseMessage response = await client.GetAsync(url))
{
using(HttpContent content = response.Content)
{
string myContent = await content.ReadAsStringAsync();
}
}
}
}
The exact same code is running successfully sometimes but sometimes returning me error. I have spent an entire day but still unable to find the reason for this weird code behavior.
Please guide me.
Atharva is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.