如何创建 HTTP 发布请求

本文关键字:布请求 请求 HTTP 创建 何创建 | 更新日期: 2023-09-27 18:34:57

你好,我是编程新手,所以我的问题可能有点奇怪。我的老板要求我使用密钥和消息创建一个 HTTP 发布请求来访问我们的客户。

我已经看过文章在 C# 控制台应用程序中处理 HTTP 请求,但它不包括我放置密钥和消息的位置,以便客户端 API 知道它。提前感谢帮助。

如何创建 HTTP 发布请求

我相信你想要这个:

    HttpWebRequest httpWReq =
    (HttpWebRequest)WebRequest.Create("http://domain.com/page.aspx");
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "username=user";
postData += "&password=pass";
byte[] data = encoding.GetBytes(postData);
httpWReq.Method = "POST";
httpWReq.ContentType = "application/x-www-form-urlencoded";
httpWReq.ContentLength = data.Length;
using (Stream stream = httpWReq.GetRequestStream())
{
    stream.Write(data,0,data.Length);
}
HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
您可以使用

WebClient

using (var client = new WebClient())
{
    // Append some custom header
    client.Headers[HttpRequestHeader.Authorization] = "Bearer some_key";
    string message = "some message to send";
    byte[] data = Encoding.UTF8.GetBytes(message);
    byte[] result = client.UploadData(data);
}

当然,根据 API 预期数据的发送方式以及它需要哪些标头,您必须调整此代码以匹配要求。