user10599435
user10599435

Reputation:

Read JSON data from stats.nba.com

I'm trying to fetch data from stats.nba.com the JSON I currently need is form the url https://stats.nba.com/stats/teamyearbyyearstats?TeamID=1610612746&LeagueID=00&PerMode=Totals&SeasonType=Regular%20Season

and I'm trying to fetch it in a c# console app. This is my code:

        try
        {
            using (var webClient = new System.Net.WebClient())
            {
                var json = webClient.DownloadString("https://stats.nba.com/stats/teamyearbyyearstats?TeamID=1610612746&LeagueID=00&PerMode=Totals&SeasonType=Regular%20Season");
                Console.WriteLine(json);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

With this, it comes out with an error of connection timed out and unable to read data from the transport connection. so I searched it up and found a solution of

ServicePointManager.Expect100Continue = false;

I put this before the using statement and it still doesn't work. Sorry I'm new to this online things, so I'm sorry if it's a noob error. Thanks

Upvotes: 0

Views: 847

Answers (2)

Alexander Petrov
Alexander Petrov

Reputation: 14251

As @Ajay pointed out, you need to add headers to the request:

using (var webClient = new WebClient())
{
    webClient.Headers.Add(HttpRequestHeader.Accept, "application/json");
    webClient.Headers.Add(HttpRequestHeader.AcceptEncoding, ": gzip, deflate, br");

    var json = webClient.DownloadString("https://stats.nba.com/stats/teamyearbyyearstats?TeamID=1610612746&LeagueID=00&PerMode=Totals&SeasonType=Regular%20Season");
    Console.WriteLine(json);
}

Upvotes: 0

Ajay
Ajay

Reputation: 554

Below code works for me.

string responsetext;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://stats.nba.com/stats/teamyearbyyearstats?TeamID=1610612746&LeagueID=00&PerMode=Totals&SeasonType=Regular%20Season");
request.Accept = "application/json";
request.Method = "GET";
request.Headers.Add("Accept-Encoding", ": gzip, deflate, br");
var response = request.GetResponse() as HttpWebResponse;
using (var responsechar = new StreamReader(response.GetResponseStream()))
{
    responsetext = responsechar.ReadToEnd();
}

response.Close();

Given url does not respond if below line is not there.

request.Headers.Add("Accept-Encoding", ": gzip, deflate, br");

Upvotes: 1

Related Questions