C#:带有POST参数的HttpClient

我使用下面的代码将POST请求发送到服务器:

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

我无法访问服务器进行调试,但我想知道,此请求是以POST还是GET发送的?

如果是GET,如何更改我的代码以将param1和param2作为POST数据发送(不在URL中)?

更清晰的替代方法是使用Dictionary来处理参数。 毕竟它们是键值对。

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

如果你不使用关键字,也不要忘记Dispose() HttpClient

正如Microsoft文档中 HttpClient类的备注部分所述,HttpClient应该被实例化一次并重新使用。

编辑:

您可能需要查看response.EnsureSuccessStatusCode(); 而不是if (response.StatusCode == HttpStatusCode.OK)

您可能希望保留HttpClient并且不要Dispose()它。 请参阅: HttpClient和HttpClientHandler是否必须处理?

正如Ben所说,你正在发布你的请求(你的代码中指定了HttpMethod.Post)

您的url中包含的查询字符串(get)参数可能不会执行任何操作。

试试这个:

 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