I'm in QA Automation, and C# isn't my first language. I've written a small class of methods for GETting and POSTing to web URLs. I use these when I want to test certain things that really fall outside the jurisdiction of Selenium, but are still roughly "black box" type testing. Link scanning, and culling data from POSTBIN, are a few examples.
I was wondering if you C# gurus might like to look the code over, and let me know if there are better ways to do what I've done, or if there's any potential gotcha's I haven't thought of:
public class RawHttp
{
public static string Url = null;
public RawHttp(string url)
{
Url = url;
}
public HttpStatusCode GetStatusCode(string url = null)
{
HttpStatusCode result = default(HttpStatusCode);
string activeUrl = url ?? Url;
var request = WebRequest.Create(activeUrl);
request.Method = "HEAD";
using (var response = request.GetResponse() as HttpWebResponse)
{
if (response != null)
{
result = response.StatusCode;
//var headers = response.Headers;
response.Close();
}
}
return result;
}
public string GetBody(string url = null)
{
string activeUrl = url ?? Url;
var request = (HttpWebRequest)WebRequest.Create(activeUrl);
request.Method = "GET";
// Set some reasonable limits on resources used by this request
request.MaximumAutomaticRedirections = 4;
request.MaximumResponseHeadersLength = 4;
// Set credentials to use for this request.
request.Credentials = CredentialCache.DefaultCredentials;
var response = (HttpWebResponse)request.GetResponse();
//Console.WriteLine("Content length is {0}", response.ContentLength);
//Console.WriteLine("Content type is {0}", response.ContentType);
// Get the stream associated with the response.
Stream receiveStream = response.GetResponseStream();
// Pipes the stream to a higher level stream reader with the required encoding format.
var readStream = new StreamReader(receiveStream, Encoding.UTF8);
var body = readStream.ReadToEnd();
response.Close();
readStream.Close();
return body;
}
public string Post(string url = null, string parameters = "")
{
string activeUrl = url ?? Url;
var req = WebRequest.Create(activeUrl);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(parameters);
req.ContentLength = bytes.Length;
Stream os = req.GetRequestStream();
os.Write(bytes, 0, bytes.Length); //Push it out there
os.Close();
var resp = req.GetResponse();
//if (resp == null) {return null;}
var sr = new System.IO.StreamReader(resp.GetResponseStream());
return sr.ReadToEnd().Trim();
}
}
Thanks!