2014-12-09 20 views
10

Io uso i codici qui sotto per inviare richiesta POST a un server:C#: HttpClient con POST parametri

string url = "http://myserver/method?param1=1&param2=2"  
HttpClientHandler handler = new HttpClientHandler(); 
HttpClient httpClient = new HttpClient(handler); 
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url); 
HttpResponseMessage response = await httpClient.SendAsync(request); 

Non ho accesso al server per eseguire il debug, ma io voglio sapere, è questa richiesta inviata come POST o GET?

Se è GET, come posso modificare il mio codice per inviare param1 & param2 come dati POST (non nell'URL)?

+3

Viene inviato come post, 'new HttpRequestMessage (HttpMethod.Post, url)', passando in 'HttpMethod.Post' si sta creando una richiesta POST. Cosa sono param1 e param2? –

+0

Prova a usare Fiddler? – SanyTiger

+0

@BenRobinson Grazie. param1 e param2 sono i miei parametri che voglio inviarli come parametri POST BUT stringa di query. –

risposta

-3

Come ha detto Ben, stai scrivendo la vostra richiesta (HttpMethod.Post specificato nel codice)

querystring (ottenere) i parametri inclusi nel tuo URL probabilmente non farà nulla.

Prova questo:

string url = "http://myserver/method";  
string content = "param1=1&param2=2"; 
HttpClientHandler handler = new HttpClientHandler(); 
HttpClient httpClient = new HttpClient(handler); 
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url); 
HttpResponseMessage response = await httpClient.SendAsync(request,content); 

HTH,

bovako

+0

@JohnCroneh questo non funziona più. Si prega di accettare l'altra risposta qui sotto! –

+0

@JohnCroneh si prega di cambiare la risposta accettata a uno che funziona –

+1

@ R.McManaman In realtà è una buona risposta se si andrebbe con la creazione di un tipo di metodo non noto. Manca un po 'di "utilizzo" per assicurarsi che sia disponibile e un "assicurarsi che sia convertito", ma segue l'implementazione del wrapper PostAsync. – HellBaby

22

un'alternativa più pulita sarebbe quella di utilizzare un Dictionary per gestire i parametri. Sono coppie di valori-chiave dopo tutto.

private static readonly HttpClient HttpClient; 

static MyClassName() 
{ 
    // HttpClient is intended to be instantiated once and re-used throughout the life of an application. 
    // Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. 
    // This will result in SocketException errors. 
    // https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.7.1 
    HttpClient = new HttpClient();  
} 

var url = "http://myserver/method"; 
var parameters = new Dictionary<string, string> { { "param1", "1" }, { "param2", "2" } }; 
var encodedContent = new FormUrlEncodedContent (parameters); 

var response = await HttpClient.PostAsync (url, encodedContent).ConfigureAwait (false); 
if (response.StatusCode == HttpStatusCode.OK) { 
    // Do something with response. Example get content: 
    // var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait (false); 
} 

Inoltre non dimenticate di Dispose() HttpClient, se non utilizzare la parola chiave using

Come indicato nella sezione Osservazioni della classe HttpClient nel Microsoft docs, HttpClient occorre istanziare una volta e riutilizzati .

Edit:

Si consiglia di guardare in response.EnsureSuccessStatusCode(); invece di if (response.StatusCode == HttpStatusCode.OK).

Si consiglia di conservare HttpClient e non Dispose() esso. Vedi: Do HttpClient and HttpClientHandler have to be disposed?

Problemi correlati