Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to POST Raw Data using C# HttpWebRequest

I am trying to make a POST request in which I am supposed to send Raw POST data.

Which property should I modify to achieve this.

Is it the HttpWebRequest.ContentType property. If, so what value should I assign to it.

like image 249
Shamim Hafiz - MSFT Avatar asked Sep 17 '10 14:09

Shamim Hafiz - MSFT


2 Answers

public static string HttpPOST(string url, string querystring)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.ContentType = "application/x-www-form-urlencoded"; // or whatever - application/json, etc, etc
    StreamWriter requestWriter = new StreamWriter(request.GetRequestStream());

    try
    {
        requestWriter.Write(querystring);
    }
    catch
    {
        throw;
    }
    finally
    {
        requestWriter.Close();
        requestWriter = null;
    }

    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    using (StreamReader sr = new StreamReader(response.GetResponseStream()))
    {
        return sr.ReadToEnd();
    }
}
like image 74
Phil Winkel Avatar answered Sep 30 '22 04:09

Phil Winkel


You want to set the ContentType property to the mime type of the data. If its a file, it depends on the type of file, if it's plain text then text/plain and if it's an arbitrary binary data of your own local purposes then application/octet-stream. In the case of text-based formats you'll want to include the charset along with the content type, e.g. "text/plain; charset=UTF-8".

You'll then want to call GetRequestStream() and write the data to the stream returned.

like image 42
Jon Hanna Avatar answered Sep 30 '22 04:09

Jon Hanna