2011-11-28 9 views
13

So che ci sono molte domande sull'invio di richieste HTTP POST con C#, ma sto cercando un metodo che usi WebClient anziché HttpWebRequest. È possibile? Sarebbe bello perché la classe WebClient è così facile da usare.Invia POST con WebClient.DownloadString in C#

So che posso impostare la proprietà Headers per impostare determinate intestazioni, ma non so se è possibile eseguire effettivamente un POST da WebClient.

risposta

13

È possibile utilizzare WebClient.UploadData() che utilizza HTTP POST, cioè .:

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

carico utile di dati specificato verrà trasmesso come il corpo POST della richiesta.

In alternativa c'è WebClient.UploadValues() per caricare una raccolta di valori nome anche tramite HTTP POST.

7

Si potrebbe usare metodo di caricamento con 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)); 
}