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

前端 未结 7 1652
醉梦人生
醉梦人生 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:29

    WebClient is sometimes easier to use than WebRequest. You may want to take a look at it.

    For JSON deserialization you are going to want to look at the JavaScriptSerializer class.

    WebClient example:

    using (WebClient client = new WebClient ())
    {
        //manipulate request headers (optional)
        client.Headers.Add (HttpRequestHeader.UserAgent, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
    
        //execute request and read response as string to console
        using (StreamReader reader = new StreamReader(client.OpenRead(targetUri)))
        {
            string s = reader.ReadToEnd ();
            Console.WriteLine (s);
        }
    }
    

    Marked as wiki in case someone wants to update the code

提交回复
热议问题