C# – Read the HTTP POST request of HttpWebRequest

chttphttpwebrequestnetpost

I need to create Http POST requests and maybe a few GET requests as strings for some tests I am writing. Currently, my tests build them using a StringBuilder and hardcoded POST requests pulled out from fiddler kinda like this:

var builder = new StringBuilder();
builder.Append("POST https://some.web.pg HTTP/1.1\r\n");
builder.Append("Content-Type: application/x-www-form-urlencoded\r\n");
builder.Append("Referer: https://some.referer.com\r\n");
builder.Append("Accept-Language: en-us\r\n");
builder.Append("Accept-Encoding: gzip, deflate\r\n");
builder.Append("User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)\r\n");
builder.Append("Host: login.yahoo.com\r\n");
//    ... other header info
builder.Append("\r\n");
builder.Append("post body......\r\n");
var postData = builder.ToString();

This is quickly making my tests messy and would prefer to have a cleaner way to build these POST requests. I've been looking into HttpWebRequest class hoping that maybe it can create these for me. I figured that behind the sences it must have some way to construct this exact request I am trying to creating in some form or another. But alas, the GetRequestStream is a writable only stream.

Is there a way to read the request stream HttpWebRequest will generate (and then change it to a string)? Or even any ideas on how to generate these POST requests would do.

Best Answer

here an msdn sample to make a Get request:

using System;

using System.Net; using System.IO;

namespace MakeAGETRequest_charp { /// /// Summary description for Class1. /// class Class1 { static void Main(string[] args) { string sURL; sURL = "http://www.microsoft.com";

        WebRequest wrGETURL;
        wrGETURL = WebRequest.Create(sURL);

        WebProxy myProxy = new WebProxy("myproxy",80);
        myProxy.BypassProxyOnLocal = true;

        wrGETURL.Proxy = WebProxy.GetDefaultProxy();

        Stream objStream;
        objStream = wrGETURL.GetResponse().GetResponseStream();

        StreamReader objReader = new StreamReader(objStream);

        string sLine = "";
        int i = 0;

        while (sLine!=null)
        {
            i++;
            sLine = objReader.ReadLine();
            if (sLine!=null)
                Console.WriteLine("{0}:{1}",i,sLine);
        }
        Console.ReadLine();
    }
}

} and here an for post request (from HTTP request with post)

    HttpWebRequest httpWReq =
    (HttpWebRequest)WebRequest.Create("http:\\domain.com\page.asp");

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 newStream = httpWReq.GetRequestStream())
{
    newStream.Write(data,0,data.Length);
}