首頁 > 軟體

HttpClient 使用

2020-06-16 17:34:50

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


IT145.com E-mail:sddin#qq.com