Ease of WebRequest example

this is and example of a generic method to execute POST WebRequests, and in this case login into a site, don't worry, the values are fake.

the 1st part is a secondary example, how to call MakeWebRequest method itself, which is the main thing in this post.

System.Collections.Specialized; - ns for NameValueCollection
NameValueCollection parameters = new NameValueCollection();

parameters.Add("textBox1", "422");
parameters.Add("textBox2", "gensearch");
parameters.Add("textBoxUserName", "UserName");
parameters.Add("textBoxPassword", "mode matchallpartial");
string strRes = "";
string url = "http://www.mysite.com/login.aspx\jsp\php\ect.";
CookieContainer cookie = new CookieContainer();

MakeWebRequest(url, "POST", ref cookie, parameters, ref strRes);

//and strRes is our response, either html or csv or whatever the resposne is
//if you dont send any params then parameters is null and mehtod is "GET"
//if you need a page that require a pre login just resend the cookie

p.s.
System.Windows.Forms.WebBrowser wb = new System.Windows.Forms.WebBrowser();
wb.DocumentText = strRes;
wb.Document.Write(strRes);

HTMLDocument doc = (HTMLDocument )wb.Document.DomDocument

public bool MakeWebRequest(String url, String method,
ref CookieContainer cookies, NameValueCollection parameters,
ref String strResponse)
{  HttpWebRequest request;
  HttpWebResponse response;
   request = (   HttpWebRequest)WebRequest.Create(url);
  request.AllowAutoRedirect = true;
  request.CookieContainer = cookies;
  request.Method = method;  if ((parameters != null) && (parameters.Count > 0))
  {      bool first = true;
      StringBuilder sbData = new StringBuilder();
      foreach (String key in parameters.AllKeys)
      {
        if (first)
          first = false;
        else
        sbData.Append("&");
        sbData.Append(HttpUtility.UrlEncode(key));
        sbData.Append("=");
        sbData.Append(HttpUtility.UrlEncode(parameters[key]));
      }
    if ("POST" == request.Method)
   {
      request.ContentType =          "application/x-www-form-urlencoded";
      request.ContentLength = sbData.Length;
   }   StreamWriter sw = new StreamWriter(request.GetRequestStream());
   sw.Write(sbData.ToString());
   sw.Close();
}
response = (
HttpWebResponse)request.GetResponse();
cookies = request.CookieContainer;
StreamReader sr = new StreamReader(response.GetResponseStream());
strResponse = sr.ReadToEnd();
sr.Close();
response.Close();

return true;
}
//end make web req


Comments

Popular posts from this blog

OverTheWire[.com] Natas Walkthrough - JUST HINT, NO SPOILERS

SOLVED The item could not be indexed successfully because the item failed in the indexing subsystem

Asp.Net Ending Response options, Response.End() vs CompleteRequest()