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

前端 未结 7 1653
醉梦人生
醉梦人生 2020-12-23 13:17

I\'m writing a small tool in C# which will need to send and receive data to/from a website using POST and json formatting. I\'ve never done anything like this before in C#

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-23 13:31

    WebRequest and more specifically the HttpWebRequest class is a good starting point for what you want to achieve. To create the request you will use the WebRequest.Create and cast the created request to an HttpWebRequest to actually use it. You will then create your post data and send it to the stream like:

    HttpWebRequest req = (HttpWebRequest)
    WebRequest.Create("http://mysite.com/index.php");
    req.Method = "POST";
    req.ContentType = "application/x-www-form-urlencoded";
    string postData = "var=value1&var2=value2";
    req.ContentLength = postData.Length;
    
    StreamWriter stOut = new
    StreamWriter(req.GetRequestStream(),
    System.Text.Encoding.ASCII);
    stOut.Write(postData);
    stOut.Close();
    

    Similarly you can read the response back by using the GetResponse method which will allow you to read the resultant response stream and do whatever else you need to do. You can find more info on the class at:

    http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx

提交回复
热议问题