Calling the API with Httpclient - POST

Asked

Viewed 958 times

0

It’s the first time I’ve developed something like this, so I don’t really know what could be wrong.

I’m making a call to an API with the HttpClient, thus:

private string autenticar()
{
    try
    {
        using (var client = new HttpClient())
        {
            string baseUrl = "/geosite-telecom-api/auth/token";
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("Mozilla", "5.0"));

            var parameters = new Dictionary<string, string> { { "username", Usuario }, { "password", Senha } };
            var encodedContent = new FormUrlEncodedContent(parameters);

            var retornos = client.PostAsync(Url + baseUrl + $"?username={Usuario}&password={Senha}", encodedContent).Result;

            return "";
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

This above code is getting the error:

The underlying connection was closed: Unexpected error in an upload.

I put the return with string empty so I can test only the connection to the API per hour.

I tested the URL on Soapui and managed to do it right.

  • I suspect something related to the HTTPS connection. Hard to be sure without knowing the details of the API being called... Can you share the documentation? A suggestion that can help: use Fiddler to capture the requisitions, both the one successfully made in Soapui and this one via code. So you can compare one call against the other and go correcting.

  • @Minelli do not know if I can still release the documentation because it seems that they release only upon payment of the service, but I will confirm and if you can put here. Anyway, I’ll test Fiddler and see how it looks. I’ll get back to you. Thanks.

  • 1

    @Minelli thank you so much man, really the problem was in HTTPS, I just modified the ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 and it worked! Thank you. If you want to put as answer, I mark as answered. Thanks!

  • Another detail is... you are doing a Post, but passing the parameters by Query String... wouldn’t it be the case to switch to GET? or remove these parameters, leaving only the encondedContent?

  • @Leandroangelo already changed that too, along with Servicepointmanager. Thank you.

1 answer

1


I researched some things on the subject, after Minelli’s comments on the question, indicating that the problem was in HTTPS.

Basically the problem is modifying the security protocol to be able to access the API. I modified the code to:

private string autenticar()
{
    try
    {
        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("Mozilla", "5.0"));

            var parameters = new Dictionary<string, string> { { "username", Usuario }, { "password", Senha } };
            var encodedContent = new FormUrlEncodedContent(parameters);

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            var retornos = client.PostAsync(Url + baseUrl, encodedContent).Result;

            var resultJson = retornos.Content.ReadAsStringAsync().Result;
            var retornoToken = Newtonsoft.Json.JsonConvert.DeserializeObject<Token>(resultJson);

            return retornoToken.token;
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

Where Url and baseUrl are already defined in the class and consist of:

Url = "https:\\site.com.br";
baseUrl = "\metodo\funcao";

The focus of the solution is on the line:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

In it I explicitly define which security protocol should be used to access the API and do not use the default protocol of the Framework.

Searching further, I found that the default . NET Framework 4.6 up protocol is the SecurityProtocolType.Tls12 and I am using the . NET Framework 4.5.

Research sources

Stack Overflow (English) Stack Overflow (English) Stack Overflow (English)

Thanks to Minelli, without him I would never have worried about security protocol.

Browser other questions tagged

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