本文介绍了C#:带有 POST 参数的 HttpClient的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码向服务器发送 POST 请求:

I use codes below to send POST request to a server:

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 发送的?

I don't have access to the server to debug but I want to know, is this request sent as POST or GET?

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

If it is GET, How can I change my code to send param1 & param2 as POST data (not in the URL)?

推荐答案

更简洁的替代方法是使用 Dictionary 来处理参数.毕竟它们是键值对.

A cleaner alternative would be to use a Dictionary to handle parameters. They are key-value pairs after all.

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

Microsoft docs,HttpClient 应实例化一次并重复使用.

As stated in the Remarks section of the HttpClient class in the Microsoft docs, HttpClient should be instantiated once and re-used.

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

您可能希望保留您的 httpclient 而不要 Dispose() 它.参见:HttpClient 和 HttpClientHandler 必须被处理吗?

You may want to keep your httpclient and dont Dispose() it. See: Do HttpClient and HttpClientHandler have to be disposed?

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

Do not worry about using .ConfigureAwait(false) in .NET Core. For more details look at https://blog.stephencleary.com/2017/03/aspnetcore-synchronization-context.html

这篇关于C#:带有 POST 参数的 HttpClient的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 05:53
查看更多