HttpClient - WebException: The underlying connection was closed: The connection was unexpectedly closed

2

I created a very simple C # console application to test connection in an API, but I can not send the request. I tried with other APIs and they worked, but this specific one I can not. It would be a query in the CartolaFC API (it's commented on in the code below, the other works).

Following code: error generated:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace ConsoleAppHttp
{
    class Program
    {

        static void Main(string[] args)
        {
            RunAsync();
        }

        static void RunAsync()
        {
            using (var clientAPI = new HttpClient())
            {
                //Um dos sites recomendava isso pra corrigir o problema, mas ainda não funciona
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11;

                clientAPI.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                //string sResponse = clientAPI.GetStringAsync("http://api.cartolafc.globo.com/mercado/status").Result; //Não Funciona
                string sResponse = clientAPI.GetStringAsync("http://jsonplaceholder.typicode.com/posts").Result; //Funciona

                Console.Write(sResponse);
            }

            Console.Read();

        }
    }
}

There is an error generated:

System.AggregateException ocorrido
  HResult=0x80131500
  Message=Um ou mais erros.
  Source=mscorlib
  StackTrace:
   em System.Threading.Tasks.Task.ThrowIfExceptional(Boolean 
includeTaskCanceledExceptions)
   em System.Threading.Tasks.Task'1.GetResultCore(Boolean 
waitCompletionNotification)
   em System.Threading.Tasks.Task'1.get_Result()
   em ConsoleAppHttp.Program.RunAsync() em e:\ricardo\documents\visual 
studio 2017\Projects\ConsoleAppHttp\ConsoleAppHttp\Program.cs:linha 32
   em ConsoleAppHttp.Program.Main(String[] args) em 
e:\ricardo\documents\visual studio 
2017\Projects\ConsoleAppHttp\ConsoleAppHttp\Program.cs:linha 21

Exceção interna 1:
HttpRequestException: Ocorreu um erro ao enviar a solicitação.

Exceção interna 2:
WebException: A conexão subjacente estava fechada: A conexão foi fechada de modo inesperado.

Would anyone have any idea how I can solve it? Can you reproduce the problem?

Note: Using VS Community 2017, Windows 10 updated.

Thank you.

    
asked by anonymous 24.06.2017 / 18:09

1 answer

1

You need to add at least User-Agent

clientAPI.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("Mozilla", "5.0"));

See the final code

static void RunAsync()
{
    using (var clientAPI = new HttpClient())
    {               
        clientAPI.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        clientAPI.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("Mozilla", "5.0"));
        string sResponse = clientAPI.GetStringAsync("http://api.cartolafc.globo.com/mercado/status").Result;

        Console.Write(sResponse);
    }

    Console.Read();

}
    
24.06.2017 / 18:48