C#:带有POST参数的HttpClient
我使用下面的代码将POST请求发送到服务器:
string url = "https://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发送的?
如果是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 = "https://myserver/method"; var parameters = new Dictionary { { "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
正如Microsoft文档中 HttpClient类的备注部分所述,HttpClient应该被实例化一次并重新使用。
编辑:
您可能需要查看response.EnsureSuccessStatusCode();
而不是if (response.StatusCode == HttpStatusCode.OK)
。
您可能希望保留HttpClient并且不要Dispose()
它。 请参阅: HttpClient和HttpClientHandler是否必须处理?
正如Ben所说,你正在发布你的请求(你的代码中指定了HttpMethod.Post)
您的url中包含的查询字符串(get)参数可能不会执行任何操作。
试试这个:
string url = "https://myserver/method"; string content = "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,content);
HTH,
bovako
上述就是C#学习教程:C#:带有POST参数的HttpClient分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/954676.html