veryon
veryon

Reputation: 21

How to create HTTP post request

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.

Upvotes: 2

Views: 19216

Answers (2)

Lucky Lefty
Lucky Lefty

Reputation: 347

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();

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1039408

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.

Upvotes: 0

Related Questions