C#:具有POST参数的HttpClient [英] C#: HttpClient with POST parameters
问题描述
我使用以下代码将POST请求发送到服务器:
I use codes below to send POST request to a server:
string url = "http://myserver/method?param1=1¶m2=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);
}
如果您不使用关键字 using
As stated in the Remarks section of the HttpClient class in the Microsoft docs, HttpClient should be instantiated once and re-used.
您可能需要研究 response.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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!