.NET HttpClient:如何动态设置请求方法?

Posted

技术标签:

【中文标题】.NET HttpClient:如何动态设置请求方法?【英文标题】:.NET HttpClient: How to set the request method dynamically? 【发布时间】:2016-12-09 17:37:23 【问题描述】:

如何使用 HttpClient 并动态设置方法而无需执行以下操作:

    public async Task<HttpResponseMessage> DoRequest(string url, HttpContent content, string method)
    
        HttpResponseMessage response;

        using (var client = new HttpClient())
        
            switch (method.ToUpper())
            
                case "POST":
                    response = await client.PostAsync(url, content);
                    break;
                case "GET":
                    response = await client.GetAsync(url);
                    break;
                default:
                    response = null;
                    // Unsupported method exception etc.
                    break;
            
        

        return response;
    

目前看来您必须使用:

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";

【问题讨论】:

可以httprequestmessage并设置方法、url和内容。然后使用httpclient的send方法 请注意,您不应针对每个请求 new HttpClient(),否则您可能会大规模耗尽您的套接字池。使用单个静态实例。 【参考方案1】:

HttpRequestMessage 包含采用 HttpMethod 实例的构造函数,但没有现成的构造函数将 HTTP 方法字符串转换为 HttpMethod,因此您无法避免该切换(以一种或另一种形式)。

但是你不应该在不同的 switch case 下有重复的代码,所以实现应该是这样的:

private HttpMethod CreateHttpMethod(string method)

    switch (method.ToUpper())
    
        case "POST":
            return HttpMethod.Post;
        case "GET":
            return HttpMethod.Get;
        default:
            throw new NotImplementedException();
    


public async Task<HttpResponseMessage> DoRequest(string url, HttpContent content, string method)

    var request = new HttpRequestMessage(CreateHttpMethod(method), url)
    
        Content = content
    ;

    return await client.SendAsync(request);

如果您不喜欢 switch,您可以使用 Dictionary 和方法字符串作为键来避免它,但是这样的解决方案不会更简单或更快。

【讨论】:

也可以将HttpMethod httpMethod作为参数传入,然后做new HttpRequestMessage(httpMethod, url)【参考方案2】:

但没有现成的构造函数将 HTTP 方法字符串转换为 HttpMethod

这不再是真的了...1

public HttpMethod(string method);

可以这样使用:

var httpMethod = new HttpMethod(method.ToUpper());

这是工作代码。

using System.Collections.Generic;
using System.Net.Http;
using System.Text;

namespace MyNamespace.HttpClient

public static class HttpClient

    private static readonly System.Net.Http.HttpClient NetHttpClient = new System.Net.Http.HttpClient();
    static HttpClient()
    

    public static async System.Threading.Tasks.Task<string> ExecuteMethod(string targetAbsoluteUrl, string methodName, List<KeyValuePair<string, string>> headers = null, string content = null, string contentType = null)
    
        var httpMethod = new HttpMethod(methodName.ToUpper());

        var requestMessage = new HttpRequestMessage(httpMethod, targetAbsoluteUrl);

        if (!string.IsNullOrWhiteSpace(content) || !string.IsNullOrWhiteSpace(contentType))
        
            var contentBytes = Encoding.UTF8.GetBytes(content);
            requestMessage.Content = new ByteArrayContent(contentBytes);

            headers = new List<KeyValuePair<string, string>>
            
                new KeyValuePair<string, string>("Content-type", contentType)
            ;
        

        headers?.ForEach(kvp =>  requestMessage.Headers.Add(kvp.Key, kvp.Value); );

        var response = await NetHttpClient.SendAsync(requestMessage);

        return await response.Content.ReadAsStringAsync();

    


【讨论】:

msdn 链接现在无法访问。请改成docs.microsoft.com/en-us/dotnet/api/… @Tsahi Ahser - 感谢您编辑资源链接!【参考方案3】:

.Net 核心

var hc = _hcAccessor.HttpContext;

var hm = new HttpMethod(hc.Request.Method.ToUpper());
var hrm = new HttpRequestMessage(hm, 'url');

【讨论】:

以上是关于.NET HttpClient:如何动态设置请求方法?的主要内容,如果未能解决你的问题,请参考以下文章

如何避免 .NET 中 HttpClient 的 DNS 失效问题?

HttpClient请求头自定义

HttpURLConnection详解

如何使用 System.Net.HttpClient 发布复杂类型?

C# HttpClient使用和注意事项,.NET Framework连接池并发限制

C# 如何将 HttpClient Keep-Alive 设置为 false