Argon
Argon

Reputation: 149

Post with parameters using HttpWebRequest in C#

Having the following code:

                var request = HttpWebRequest.Create("https://api.channeladvisor.com/oauth2/token");
            request.ContentType = "text/html";               
            request.Method = "POST";
            request.Headers.Add("cache-control","no-cache");
            request.Headers.Add("Authorization", "Basic " + Base64Translator.ToBase64(System.Text.Encoding.ASCII, devKey+":"+sharedSecret));          

            string postData = " grant_type=refresh_token&refresh_token=a12SL1bHhJwerxM2NFth2efZw0yIW7462kAhR43UCJA";

            var data = Encoding.ASCII.GetBytes(postData);
            request.ContentLength = data.Length;

            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }

            var response = (HttpWebResponse)request.GetResponse();
            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

What's wrong? I can't do the request but I can using external programs like Postman. Do you see anything wrong in the header?

Error: "The remote server returned an error: (400) Bad Request."

Thanks!

Upvotes: 4

Views: 8964

Answers (1)

EylM
EylM

Reputation: 6103

Your content type should be application/x-www-form-urlencoded.

request.ContentType = "application/x-www-form-urlencoded";

Upvotes: 2

Related Questions