C# HttpClient用法

因为HttpClilent中默认的Cookie是登录完成后自带的,如果需要设置Cookie要先把默认的cookie设置为false:

using (HttpClient client = new HttpClient(new HttpClientHandler() { UseCookies = false }))
using (HttpClient client = new HttpClient(new HttpClientHandler() { UseCookies = false }))
            {
                client.DefaultRequestHeaders.Add("Cookie", @"xxxxxx");
            }
View Code

Get请求

//Get请求添加Header
        public static string GetWithHeader(string url)
        {
            using (HttpClient httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Add("Authorization", @"Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJndWlkIjoibXItMjAyMS0xMC0yNS1nSlJfWXNNQmJuLTJYeTYwYjA5WUVfMGpWN3RUT1h4MmY1Y3JFQ3pPNmdpT1V1czFaQktNLUhEV1NUOEd1ZlZtTHZVY01yay1JSSIsImlhdCI6MTYzNTE0Mjg5NCwiaXNzIjoiZGF0YS5taWRsYW5kLmNvbS5oayJ9.OpYHdETIud_WWzSl1eIhLL18oUZLX9ZNYqqtCQlmV7KqH7Djckp_6StjtjR3NrRrWUuRYAHyUv_idq3IajN9TyK2YvJd1pDkfT_U-do7pchb3muSx6x1LkWhpJSO4F-x2_0AounUcGTuaSpy1DrkoHVClqmeVyo4CVOP9DOcYtBVl-di0v2N6FGtiwFdjhunO4J0530sMCTIPcQHV9MF5AjqqrCLadCsf641NkZUCiAcicuCmi2c5R6rdsMaVPOoL1dXbtFpmeLd2Os6wioHgmK_c5cB90uqh4Sk7vJKm_eKi2ErXhHshGi56pZcnJNjfe4_T04ojD7Gbaf2oDm08BOjEXr7uVH5HcJ-WE4FLpZKmQolmtFQj276mhkSeEorx15WjIhjaaiFmeUsbXcbEt9V8FdMX2ZGWPpkK3BE70mg78_pB7-VSe6-gLflPooEliKz8fMx6T362e5KhZzJNhf7FJtzROMtzWelXMbnycYg_fXeVc0mxf-W7XLexYw6xDaFQEnj1mSoEtLW1S1b41ztp49IKua5oWuEzI0EqOXFXl1h5EEiNhcMYQB7oV5tQd5h74ppZGBpw4jL9J8EyelnX-MwqXR6SEwBj3f8JQkAB4tbYTNA0Lzg35sGSUpUU9ofLzMtafEMSmOLGJy7cOsatR258cRlGSAg-nvjfCE");
                HttpResponseMessage res = httpClient.GetAsync(url).Result;
                return res.Content.ReadAsStringAsync().Result;
            }
        }
View Code

POST请求

Post  =>application/json

//post 请求 Json字符串FromBody  //application/json
        public static string PostWithJsonFromBody(string url,string jsonStr)
        {
            using (HttpClient client = new HttpClient())
            {
                //添加头部
                //client.DefaultRequestHeaders.Add("","");
                HttpContent httpContent = new StringContent(jsonStr);
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                httpContent.Headers.ContentType.CharSet = "utf-8";
                HttpResponseMessage responseMessage = client.PostAsync(url, httpContent).Result;
                return responseMessage.Content.ReadAsStringAsync().Result;
            }
        }
View Code

 

Post  =>application/x-www-form-urlencoded

 // application/x-www-form-urlencoded
        public static string PostWithFromUrlEncodedContent(string url, string Str)
        {
            using (HttpClient client = new HttpClient(new HttpClientHandler() { UseCookies = false }))
            {
                client.DefaultRequestHeaders.Add("Cookie", @"GA1.1.2114479464.1637811521; _ga_N1VDTN21FS=GS1.1.1637821074.2.1.1637821075.0; _fbp=fb.2.1637821075754.2122594005; XSRF-TOKEN=eyJpdiI6InpaZHFUNUNcL2hCNFJrU2l1MER5dUdBPT0iLCJ2YWx1ZSI6InpOWVpVMkZWM01uRHNQcXUxN25uQjdDaENYNnEyTlgwVTkwQU45UUtcL0VvYXdoWmJuUFl2MUZLRWRjVnFiUVwvbCIsIm1hYyI6ImJmZmY0YzZkNmJhMzhkMTJiOWUzNDFhYjNiZTUyNWQ0MjU5MDJlNDI0MTQ4ODQ1YmNjNGI3MDc4NTEzMTdmZGYifQ%3D%3D; professional_properties_co_session=eyJpdiI6Im5yRGVmOVEwS1E2WCtpMU56bk1Fc3c9PSIsInZhbHVlIjoiR1BnU0d6OFJJVFlSTGp3RlhXaThGWTVFaGtYNDZ4aGgrSFNRSHBhQkdvQ3F5NGdsMGRQMkJBV1hCOUhGeWVociIsIm1hYyI6IjYxZDAxMWY1OWJkOWY1NTM4ZDU5ZjJhMDQ5OWU0YjFkZmI2MzE4Y2YxOTNmYjY5OWJlZTdlNzA5N2FkMWYyM2UifQ%3D%3D");
                HttpContent httpContent = new FormUrlEncodedContent(Helper.FormDataToDictionary(Str));
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
                httpContent.Headers.ContentType.CharSet = "utf-8";
                HttpResponseMessage responseMessage = client.PostAsync(url, httpContent).Result;
                return responseMessage.Content.ReadAsStringAsync().Result;
            }
        }
View Code

model转成x-www-form-urlencoded类型的参数

public static string ToPaeameter(object source)
        {
            var buff = new StringBuilder(string.Empty);
            if (source == null)
                throw new ArgumentNullException("source", "Unable to convert object to a dictionary. The source object is null.");
            foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(source))
            {
                object value = property.GetValue(source);
                if (value != null)
                {
                    buff.Append(WebUtility.UrlEncode(property.Name) + "=" + WebUtility.UrlEncode(value + "") + "&");
                }
            }
            return buff.ToString().Trim('&');
        }
View Code

x-www-form-urlencoded类型的viewparse转成Dictionary:(页面copy获取)

public static Dictionary<string, string> FormDataToDictionary(string viewParse_Encode)
        {
            var viewParse = HttpUtility.UrlDecode(viewParse_Encode, Encoding.UTF8);
            Dictionary<string, string> dic = new Dictionary<string, string>();
            var arr = viewParse.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var a in arr)
            {
                var arr2 = a.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
                if (arr2.Length == 1)
                {
                    string s = string.Empty;
                    dic.Add(arr2[0], s);
                }
                else
                    dic.Add(arr2[0], arr2[1]);
            }
            return dic;
        }
View Code

 

Post  =>multipart/form-data 

public static void UploadFile(string taskId, string filePath)
        {
            var fileName = Path.GetFileName(filePath);
            var uploadUrl = @"https://******.cn/api/upload";
            using (HttpClient client = new HttpClient())
            {
                var content = new MultipartFormDataContent();
                //content.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");//这条不能加
                content.Add(new StringContent($"{appId}"), "app_id");//参数;注意:这里前面为value,后面为key,跟字典相反
                content.Add(new StringContent($"{signa}"), "signa");
                FileStream fStream = File.Open(filePath, FileMode.Open, FileAccess.Read);
                content.Add(new StreamContent(fStream, (int)fStream.Length), "content", fileName);//文件;content为文件参数名称
                var res = client.PostAsync(uploadUrl, content).GetAwaiter().GetResult().Content.ReadAsStringAsync().Result;
                Console.WriteLine(res);
            }
        }
View Code

 

Post   =>application/octet-stream

            using (var client = new HttpClient())
            {
                FileStream fStream = File.Open(filePath, FileMode.Open, FileAccess.Read);
                HttpContent content = new StreamContent(fStream);
                content.Headers.ContentLength = fStream.Length;
                var res = client.PostAsync(url, content).GetAwaiter().GetResult().Content.ReadAsStringAsync().Result;
                Console.WriteLine(res);
            }
View Code

 

Send方法:

//Send请求,先配置请求参数,HttpRequestMessage
        public static string SendAsPost(string url,string content)
        {
            var handler = new HttpClientHandler() { UseCookies = false};
            using (HttpClient client = new HttpClient(handler))
            {
                HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post,url);
                requestMessage.Headers.Add("Cookie", @"_ga=GA1.1.2114479464.1637811521; _ga_N1VDTN21FS=GS1.1.1637821074.2.1.1637821075.0; _fbp=fb.2.1637821075754.2122594005; XSRF-TOKEN=eyJpdiI6InpaZHFUNUNcL2hCNFJrU2l1MER5dUdBPT0iLCJ2YWx1ZSI6InpOWVpVMkZWM01uRHNQcXUxN25uQjdDaENYNnEyTlgwVTkwQU45UUtcL0VvYXdoWmJuUFl2MUZLRWRjVnFiUVwvbCIsIm1hYyI6ImJmZmY0YzZkNmJhMzhkMTJiOWUzNDFhYjNiZTUyNWQ0MjU5MDJlNDI0MTQ4ODQ1YmNjNGI3MDc4NTEzMTdmZGYifQ%3D%3D; professional_properties_co_session=eyJpdiI6Im5yRGVmOVEwS1E2WCtpMU56bk1Fc3c9PSIsInZhbHVlIjoiR1BnU0d6OFJJVFlSTGp3RlhXaThGWTVFaGtYNDZ4aGgrSFNRSHBhQkdvQ3F5NGdsMGRQMkJBV1hCOUhGeWVociIsIm1hYyI6IjYxZDAxMWY1OWJkOWY1NTM4ZDU5ZjJhMDQ5OWU0YjFkZmI2MzE4Y2YxOTNmYjY5OWJlZTdlNzA5N2FkMWYyM2UifQ%3D%3D");
                requestMessage.Headers.Add("accept-language", "zh-CN,zh;q=0.9,en;q=0.8");
                requestMessage.Content = new FormUrlEncodedContent(Helper.FormDataToDictionary(content));
                HttpResponseMessage responseMessage =  client.SendAsync(requestMessage).Result;
                return responseMessage.Content.ReadAsStringAsync().Result;
            }
        }
View Code

 

HttpContent各种格式:

MultipartFormDataContent===================>multipart/form-data                    

FormUrlEncodedContent===================>application/x-www-form-urlencoded

StringContent===================>application/json   (常用)

StreamContent===================>application/octet-stream    /    binary

posted @ 2021-11-25 17:58  点终将连成线  阅读(992)  评论(0编辑  收藏  举报