【问题标题】:Post with parameters using HttpWebRequest in C#在 C# 中使用 HttpWebRequest 发布参数
【发布时间】:2017-08-21 15:18:07
【问题描述】:

有以下代码:

                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."

谢谢!

【问题讨论】:

  • 错误是什么?
  • 尝试将您的请求与使用 Fiddler 的良好请求进行比较。

标签: c# post httpwebrequest


【解决方案1】:

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

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

【讨论】:

  • 抱歉忘记添加了!
  • 我做到了!错误:“远程服务器返回错误:(400) 错误请求。”
  • 猜猜:你在 PostData 中有一个前导空格。
  • 呵呵我尝试添加一个空格(我的测试中的1个......)但没有空格仍然无法工作:'(
猜你喜欢
  • 2023-01-31
  • 1970-01-01
  • 2013-01-20
  • 1970-01-01
  • 1970-01-01
  • 2019-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多