harishr
harishr

Reputation: 18065

read csv file from url using httpclient

I am trying to read csv using HttpClient

    [Test, Explicit]
    public async Task ImportSymbolsTestAsync()
    {
        var url = "https://nsearchives.nseindia.com/content/equities/EQUITY_L.csv";
        ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls13 | SecurityProtocolType.Tls12;
        var response = await new HttpClient().GetAsync(url);
        response.EnsureSuccessStatusCode();
    }

But getting error

Message:  System.Net.Http.HttpRequestException : An error occurred while sending the request. ----> System.IO.IOException : Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.. ----> System.Net.Sockets.SocketException : An existing connection was forcibly closed by the remote host.

Stack Trace:  HttpConnection.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken) HttpConnectionPool.SendWithVersionDetectionAndRetryAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken) RedirectHandler.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)

If I try the same thing with postman, then it works. What could be the issue?

Upvotes: 0

Views: 124

Answers (1)

Jesse C. Slicer
Jesse C. Slicer

Reputation: 20157

Make sure you're using HttpClient properly:

private static readonly HttpClient _Client = new HttpClient();

static MyTestClass()
{
    ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls13 | SecurityProtocolType.Tls12;
}

[Test, Explicit]
public async Task ImportSymbolsTestAsync()
{
    var url = "https://nsearchives.nseindia.com/content/equities/EQUITY_L.csv";
    using (var response = await _Client.GetAsync(url))
    {
        response.EnsureSuccessStatusCode();
    }
}

Upvotes: 0

Related Questions