2

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

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

4

2 回答 2

2

我相信你想要这个:

    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();
于 2013-10-11T09:30:44.607 回答
0

您可以使用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 期望如何发送数据以及它需要哪些标头,您必须调整此代码以匹配要求。

于 2013-10-11T09:19:56.523 回答