如何创建HTTP post请求

时间:2013-10-11 09:17:34

标签: c# api http request

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

我已经看过文章Handle HTTP request in C# Console application,但它没有包含我放置密钥和消息的位置,因此客户端API知道它。提前感谢帮助。

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分: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预期数据的发送方式以及需要的标头,您必须调整此代码以符合要求。