haijiandong
3/21/2018 - 8:49 AM

c# HTTP请求帮助类

c# HTTP请求帮助类

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Common
{
    public class HttpHelper
    {
        public static async Task<string> HttpGetAsync(string url, bool isCook = true)
        {
            var baseAddress = new Uri(url);
            using (var httpClient = new HttpClient() { BaseAddress = baseAddress })
            {
                //var message = new HttpRequestMessage(HttpMethod.Get, baseAddress);
                //var message = new HttpRequestMessage(HttpMethod.Put, baseAddress);
                var message = new HttpRequestMessage(HttpMethod., baseAddress);
                httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
                httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding", "UTF-8");//("Accept-Encoding", "gzip, deflate"); //
                //httpClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Mobile Safari/537.36");
                httpClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.89 Safari/537.36");
                httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Charset", "ISO-8859-1");
                if (isCook) httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Cookie", "UUUXXX");

                var response = await httpClient.SendAsync(message);
                response.EnsureSuccessStatusCode();
                var resultModel = await response.Content.ReadAsByteArrayAsync();
                return Encoding.UTF8.GetString(resultModel);
            }
        }
    }
}