gpt4 book ai didi

C#:带有 POST 参数的 HttpClient

转载 作者:IT王子 更新时间:2023-10-29 04:30:02 26 4
gpt4 key购买 nike

我使用下面的代码向服务器发送 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://learn.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 docs 中 HttpClient 类的备注部分所述, HttpClient 应实例化一次并重新使用。

编辑:

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

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

编辑:

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

关于C#:带有 POST 参数的 HttpClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27376133/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com