感谢支持
我们一直在努力

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

Java语言使用HttpClient模拟浏览器登录  http://www.linuxidc.com/Linux/2016-05/131214.htm

HttpClient4.3 关于https 中SSL证书请求问题 http://www.linuxidc.com/Linux/2016-04/130090.htm

HttpClient4 用法 由HttpClient3 升级到 HttpClient4 必看  http://www.linuxidc.com/Linux/2015-06/119100.htm

HttpClient 教程  http://www.linuxidc.com/Linux/2015-06/119099.htm

使用HttpClient实现文件的上传下载 http://www.linuxidc.com/Linux/2014-07/104303.htm

Android 实现 HttpClient 请求Https  http://www.linuxidc.com/Linux/2014-05/102306.htm

Android使用HttpClient下载图片 http://www.linuxidc.com/Linux/2014-05/101855.htm

HttpClient使用详解  http://www.linuxidc.com/Linux/2014-08/104945.htm

本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-08/134582.htm

赞(0) 打赏
转载请注明出处:服务器评测 » HttpClient 使用
分享到: 更多 (0)

听说打赏我的人,都进福布斯排行榜啦!

支付宝扫一扫打赏

微信扫一扫打赏