How to post data to specific URL using WebClient in C#

后端 未结 8 1679
深忆病人
深忆病人 2020-11-22 07:12

I need to use \"HTTP Post\" with WebClient to post some data to a specific URL I have.

Now, I know this can be accomplished with WebRequest but for some reasons I wa

8条回答
  •  感动是毒
    2020-11-22 08:01

    There is a built in method called UploadValues that can send HTTP POST (or any kind of HTTP methods) AND handles the construction of request body (concatenating parameters with "&" and escaping characters by url encoding) in proper form data format:

    using(WebClient client = new WebClient())
    {
        var reqparm = new System.Collections.Specialized.NameValueCollection();
        reqparm.Add("param1", " kinds & of = ? strings");
        reqparm.Add("param2", "escaping is already handled");
        byte[] responsebytes = client.UploadValues("http://localhost", "POST", reqparm);
        string responsebody = Encoding.UTF8.GetString(responsebytes);
    }
    

提交回复
热议问题