Send POST with WebClient.DownloadString in C#

蓝咒 提交于 2019-12-22 02:01:16

问题


I know there are a lot of questions about sending HTTP POST requests with C#, but I'm looking for a method that uses WebClient rather than HttpWebRequest. Is this possible? It'd be nice because the WebClient class is so easy to use.

I know I can set the Headers property to have certain headers set, but I don't know if it's possible to actually do a POST from WebClient.


回答1:


You can use WebClient.UploadData() which uses HTTP POST, i.e.:

using (WebClient wc = new WebClient())
{
    byte[] result = wc.UploadData("http://stackoverflow.com", new byte[] { });
}

The payload data that you specify will be transmitted as the POST body of your request.

Alternatively there is WebClient.UploadValues() to upload a name-value collection also via HTTP POST.




回答2:


You could use Upload method with HTTP 1.0 POST

string postData = Console.ReadLine();

using (System.Net.WebClient wc = new System.Net.WebClient())
{
    wc.Headers.Add("Content-Type","application/x-www-form-urlencoded");
    // Upload the input string using the HTTP 1.0 POST method.
    byte[] byteArray = System.Text.Encoding.ASCII.GetBytes(postData);
    byte[] byteResult= wc.UploadData("http://targetwebiste","POST",byteArray);
    // Decode and display the result.
    Console.WriteLine("\nResult received was {0}",
                      Encoding.ASCII.GetString(byteResult));
}


来源:https://stackoverflow.com/questions/8290390/send-post-with-webclient-downloadstring-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!