0

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

  • have a look on this => https://stackoverflow.com/questions/5420656/unable-to-read-data-from-the-transport-connection-an-existing-connection-was-f – er-sho Nov 03 '18 at 07:36

2 Answers2

1

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");
Ajay
  • 444
  • 2
  • 9
0

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);
}
Alexander Petrov
  • 13,457
  • 2
  • 20
  • 49
  • oh I see. I didn't thought I would have to add a header. Since if I have to access the api on google chrome I would just use it as an url. thanks –  Nov 06 '18 at 14:28