zoukankan      html  css  js  c++  java
  • HttpClient 使用

    Api支持

    HttpClient 是基于Task的异步方法组,支持取消、超时异步特性,其可以分类为以下:

    Restful: GetAsync,PostAsync,DeleteAsync,PutAsync

    HttpHeaders属性:DefaultRequestHeaders

    Timeout属性:Timeout,相比HttpRequest的参数,更加地智能,用TimeSpan替换了int。

    Get扩展(本质上是封装了GetAsync()):GetStringAsync,GetStreamAsync,

    GetByteArrayAsync

    SendAsync:Restful的实现应该是封装了此方法。需要一个HttpRequestMessage作为参数。

    HttpContent

    使用post方式请求示例:

    
    public static async Task<string> CreateUrlAsync(string url, Dictionary<string, string> parameters, string accessToken, int timeount = 10)
    {
        HttpClient httpClient = new HttpClient(new MyHttpClientHandlerProxy(accessToken));
        httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
        httpClient.Timeout = TimeSpan.FromSeconds(timeount);
    
        FormUrlEncodedContent content = new FormUrlEncodedContent(parameters);
        var response = await httpClient.PostAsync(url, content);
        var str = await response.Content.ReadAsStringAsync();
    
        return str;
    }
    

    其他的Content类型:

    StreamContent,StringContent,MutilpartContent,MultipartFormDataContent

    HttpClientHandler

    作为一个代理角色,可以支持自定义的处理方式。

    public class MyHttpClientHandlerProxy : HttpClientHandler
    {
        private string accessToken;
        public MyHttpClientHandlerProxy(string accessToken)
        {
            this.accessToken = accessToken;
        }
    
        protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            //处理Headers
            request.Headers.Referrer = new Uri("www.imctf.com");
            request.Headers.Add("Authorization", "Bearer " + accessToken);
            request.Headers.Add("UserAgent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727)");
    
            //执行
            var response = await base.SendAsync(request, cancellationToken);
    
            //处理编码
            var contentType = response.Content.Headers.ContentType;
            if (string.IsNullOrEmpty(contentType.CharSet))
            {
                contentType.CharSet = "GBK";
            }
    
            return response;
        }
    }
    

    使用:

    HttpClient httpClient = new HttpClient(new MyHttpClientHandlerProxy(accessToken));
    
  • 相关阅读:
    ecshop首页最新评论的调用
    在ECSHOP商品列表页显示每个商品的评论等级和评论数量
    ecshop 系统信息在哪个页面
    ECSHOP去版权_ECSHOP2.7.2去版权方法最新方法
    ECShop 自定义函数以及调用
    ecshop 首页如何调用积分商城里面的的商品
    回到顶部的js代码
    ./flow.php (购物流程)
    C#把字符串转时间格式
    如何将服务端的多个文件打包下载(转)
  • 原文地址:https://www.cnblogs.com/pengzhen/p/5784804.html
Copyright © 2011-2022 走看看