How to create HTTP post request

2020-04-14 16:14发布

Hello I'm new at programing so my question might be a little bit odd. My boss ask me to create a HTTP post request using a key and a message to access our client.

I already seen the article Handle HTTP request in C# Console application but it doesn't include where I put the key and message so the client API knows its me. Appreciate the help in advance.

2条回答
2楼-- · 2020-04-14 16:30

I believe you wanted this:

    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();
查看更多
Animai°情兽
3楼-- · 2020-04-14 16:51

You could use a 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);
}

Of course depending on how the API expects the data to be sent and which headers it requires you will have to adapt this code to match the requirements.

查看更多
登录 后发表回答