如何在C#中使用HttpWebRequest传递标头和正文值?

时间:2019-05-22 09:34:52

标签: c# api integration httpwebresponse

我正在尝试通过C#中的HttpWebRequest类将API凭证数据发布到API,就像我必须在Header中传递“ Content-Type:application / x-www-form-urlencoded” 一样,在主体中传递“ grant_type:client_credentials,client_id:ruban123,client_secret:123456” 以获得响应/令牌(如API参考中所述)。

以下我附加了我所做的工作

.as-console-wrapper { max-height: 100% !important; top: 0; }

2 个答案:

答案 0 :(得分:0)

此处正确的HttpWebRequest使用:

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(pathapi);
    request.Method = "POST";
    string postData = "grant_type=client_credentials&client_id=ruban123&client_secret=123456";
    ASCIIEncoding encoding = new ASCIIEncoding();
    byte[] bytes = encoding.GetBytes(postData);

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

    request.ContentLength = bytes.Length;
    Stream newStream = request.GetRequestStream();
    newStream.Write(bytes, 0, bytes.Length);

    HttpWebResponse response = request.GetResponse() as HttpWebResponse;

HttpWebRequest方法不相关。看看这个问题Setting Authorization Header of HttpClient

答案 1 :(得分:0)

似乎您错过了HttpWebRequest的ContentLength属性的设置。它应该等于要发送的字节数。

请点击此链接以获取更多信息:

https://docs.microsoft.com/en-us/dotnet/api/system.net.httpwebrequest.contentlength?view=netframework-4.8