0

My method to get tokenKey is :

        HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url);
        httpRequest.Method = "POST";
        httpRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36 OPR/52.0.2871.99";

        string tokenResponse = null;

        HttpClient client = new HttpClient();

        HttpResponseMessage response = null;
        try
        {
            client.DefaultRequestHeaders.Add("x-api-key", "key");
            if (method.Equals("POST"))
            {

                httpRequest.Accept = "application/json";
                httpRequest.ContentType = "application/json";

                var data = @"{""username"":@"""+ login + @""",""password"" :@"""+ password + @"""}";

                using (var streamWriter = new StreamWriter(httpRequest.GetRequestStream()))
                {
                    streamWriter.Write(data);
                }

                var httpResponse = (HttpWebResponse)httpRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                  tokenResponse = streamReader.ReadToEnd();
                }
            }
       }
catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }

        return tokenResponse;

after var httpResponse = (HttpWebResponse)httpRequest.GetResponse(); this error msg: The underlying connection was closed: Unexpected error on a send.

x-api-key is okay but i don't put the original as the username and password i do it easy with postman postman request done

Can anyone help me understand where I'm going wrong?

  • Try to use JsonConvert.Serialize method to create JSON value – Serhii Feb 09 '22 at 22:29
  • Why are you catching the exception...only to throw a new exception with the original message but nothing else? That pattern is not very good, because you lose the stack trace, and any other important info from the exception. In this case, there's no point using a try/catch block at all. It adds nothing of value, and should be removed from this code. – mason Feb 10 '22 at 02:31

2 Answers2

0

Could this be a case of mismatch TLS versions? See this answer here: C# HttpWebRequest The underlying connection was closed: An unexpected error occurred on a send

Also it looks like your HttpWebRequest won't have the correct headers, because you are setting them on the HttpClient object instead. The HttpClient also doesn't seem to be being used for this call.

Max Wesley
  • 21
  • 5
  • About httpClient sorry it's beacause i put only post part and forgot to delete httpClient to my get use And about this answer is not good, i've try it. – Gabriel Carvalho Feb 10 '22 at 11:37
0

See documentation, how to use HttpWebRequest and how to write body properly to request. I think the problem is with a request stream.

Serhii
  • 723
  • 1
  • 4
  • 12