繁体   English   中英

C#:带有 POST 参数的 HttpClient

[英]C#: HttpClient with POST parameters

我使用下面的代码向服务器发送 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<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() httpclient,如果你不使用关键字using

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

编辑:

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

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

编辑:

不要担心在 .NET Core 中使用 .ConfigureAwait(false)。 有关更多详细信息,请查看https://blog.stephencleary.com/2017/03/aspnetcore-synchronization-context.html

正如本所说,您正在发布您的请求(在您的代码中指定 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);

哈,

博瓦科

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM