簡體   English   中英

在C#中使用WebClient.DownloadString發送POST

[英]Send POST with WebClient.DownloadString in C#

我知道有很多關於使用C#發送HTTP POST請求的問題,但我正在尋找一種使用WebClient而不是HttpWebRequest 這可能嗎? 這很好,因為WebClient類很容易使用。

我知道我可以設置Headers屬性以設置某些標頭,但我不知道是否可以從WebClient實際執行POST。

您可以使用使用HTTP POST的WebClient.UploadData() ,即:

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

您指定的有效負載數據將作為請求的POST正文傳輸。

或者, WebClient.UploadValues()也通過HTTP POST上傳名稱 - 值集合。

您可以使用HTTP 1.0 POST的Upload方法

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));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM