使用C#中的HttpWebRequest发布参数

时间:2017-08-21 15:18:08

标签: c# post httpwebrequest

拥有以下代码:

                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();

怎么了?我不能做请求,但我可以使用像Postman这样的外部程序。你看到标题有什么不对吗?

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

谢谢!

1 个答案:

答案 0 :(得分:1)

您的内容类型应为application / x-www-form-urlencoded。

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