Error while consuming Github API V3 using Httpclient or even Httpwebrequest

Asked

Viewed 234 times

1

I’m unable to consume the Github V3 API with basic authentication (without using Octokit). I know it works with Restsharp but I want to know why it doesn’t work with HttpClient and HttpWebRequest.

I always get the same answer :

"A protocol breach error occurred"

Just follow my code:

using (var client = new HttpClient())
{
    var response = client.GetAsync("https://api.github.com/emojis").Result;

    if (response.IsSuccessStatusCode)
    {
        var responseContent = response.Content; 
        string responseString = responseContent.ReadAsStringAsync().Result;

        Console.WriteLine(responseString);
    }
}

1 answer

0


To use Httpclient recommend using async and await for the calls, which makes the code efficient for external calls, I performed a test and it worked, follow the code, remembering that it was necessary to inform a Header.

public async Task GetGithub(){
      using (var client = new HttpClient())
      {
        client.DefaultRequestHeaders.Add("User-Agent", "Other");

        var response = await client.GetAsync("https://api.github.com/emojis");

        if (response.IsSuccessStatusCode)
        {
            var responseContent = response.Content; 
            string responseString = await responseContent.ReadAsStringAsync();

            Console.WriteLine(responseString);
        }
    }
}
  • Thank you very much, I already use with async and await more was already testing everything without finding the problem, that was Header, only put the header that used and worked

Browser other questions tagged

You are not signed in. Login or sign up in order to post.