C#:带有POST参数的HttpClient

时间:2014-12-09 10:01:54

标签: c# post parameters 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中)?

2 个答案:

答案 0 :(得分:42)

更清洁的替代方案是使用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<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);
}

如果你不使用关键字Dispose()

,也不要忘记using HttpClient

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

编辑:

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

你可能希望保留你的HttpClient并且不要Dispose()它。请参阅:Do HttpClient and HttpClientHandler have to be disposed?

答案 1 :(得分:-7)

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

您的网址中包含的查询字符串(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