code_junkie

Is WebRequest The Right C# Tool For Interacting With Websites?

Nov 10th, 2011
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.81 KB | None | 0 0
  1. HttpWebRequest req = (HttpWebRequest)
  2. WebRequest.Create("http://mysite.com/index.php");
  3. req.Method = "POST";
  4. req.ContentType = "application/x-www-form-urlencoded";
  5. string postData = "var=value1&var2=value2";
  6. req.ContentLength = postData.Length;
  7.  
  8. StreamWriter stOut = new
  9. StreamWriter(req.GetRequestStream(),
  10. System.Text.Encoding.ASCII);
  11. stOut.Write(postData);
  12. stOut.Close();
  13.  
  14. using (WebClient client = new WebClient ())
  15. {
  16. //manipulate request headers (optional)
  17. client.Headers.Add (HttpRequestHeader.UserAgent, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
  18.  
  19. //execute request and read response as string to console
  20. using (StreamReader reader = new StreamReader(client.OpenRead(targetUri)))
  21. {
  22. string s = reader.ReadToEnd ();
  23. Console.WriteLine (s);
  24. }
  25. }
Add Comment
Please, Sign In to add comment