首页 > 编程语言 >C# HttpClient发送Get和Post请求

C# HttpClient发送Get和Post请求

时间:2023-05-16 11:13:21浏览次数:44  
标签:string Get C# headers header client Post null HttpClient

 HttpClient发送Get和Post请求

 

public class HttpHelper
    {
        /// <summary>
        /// 发起POST同步请求
        /// 
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
        /// <param name="headers">填充消息头</param>        
        /// <returns></returns>
        public static string HttpPost(string url, string postData = null, string contentType = null, int timeOut = 30, Dictionary<string, string> headers = null)
        {
            postData = postData ?? "";
            using (HttpClient client = new HttpClient())
            {                
                client.Timeout = new TimeSpan(0, 0, timeOut);
                if (headers != null)
                {
                    foreach (var header in headers)
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
                using (HttpContent httpContent = new StringContent(postData, Encoding.UTF8))
                {
                    if (contentType != null)
                        httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);

                    HttpResponseMessage response = client.PostAsync(url, httpContent).Result;
                    return response.Content.ReadAsStringAsync().Result;
                }
            }
        }


        /// <summary>
        /// 发起POST异步请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
        /// <param name="headers">填充消息头</param>        
        /// <returns></returns>
        public static async Task<string> HttpPostAsync(string url, string postData = null, string contentType = null, int timeOut = 30, Dictionary<string, string> headers = null)
        {
            postData = postData ?? "";
            using (HttpClient client = new HttpClient())
            {
                client.Timeout = new TimeSpan(0, 0, timeOut);
                if (headers != null)
                {
                    foreach (var header in headers)
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
                using (HttpContent httpContent = new StringContent(postData, Encoding.UTF8))
                {
                    if (contentType != null)
                        httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);

                    HttpResponseMessage response = await client.PostAsync(url, httpContent);
                    return await response.Content.ReadAsStringAsync();
                }
            }
        }

        /// <summary>
        /// 发起GET同步请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="headers"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public static string HttpGet(string url, Dictionary<string, string> headers = null)
        {
            using (HttpClient client = new HttpClient())
            {
                if (headers != null)
                {
                    foreach (var header in headers)
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
                else
                {
                    client.DefaultRequestHeaders.Add("ContentType", "application/x-www-form-urlencoded");
                    client.DefaultRequestHeaders.Add("UserAgent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
                }
                try
                {
                    HttpResponseMessage response = client.GetAsync(url).Result;
                    return response.Content.ReadAsStringAsync().Result;
                }
                catch (Exception ex)
                {
                    //TODO 打印日志
                    Console.WriteLine($"[Http请求出错]{url}|{ex.Message}");
                }
                return "";
            }
        }

        /// <summary>
        /// 发起GET异步请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="headers"></param>
        /// <returns></returns>
        public static async Task<string> HttpGetAsync(string url, Dictionary<string, string> headers = null)
        {
            using (HttpClient client = new HttpClient())
            {
                if (headers != null)
                {
                    foreach (var header in headers)
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
                HttpResponseMessage response = await client.GetAsync(url);
                return await response.Content.ReadAsStringAsync();
            }
        }
HttpClient

 

标签:string,Get,C#,headers,header,client,Post,null,HttpClient
From: https://www.cnblogs.com/love201314/p/17404328.html

相关文章

  • springboot 整合webservice 相关说明
    1.环境依赖jdk8,springboot2.3.12.release,cxf版本需要根据springboot版本修改,方法:查看springboot版本的发布日期,然后根据日期找相近的两个版本<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId><versi......
  • CSS选择器有哪些
    CSS选择器是用来选择HTML或XML元素的一种方式,CSS选择器可以根据元素的标签名、类名、ID、属性值等特征进行选择。以下是一些常用的CSS选择器:标签选择器:使用元素的标签名作为选择器,例如:p、h1、div等。类选择器:选择具有指定类名的元素,使用“.类名”作为选择器,例如:.demo。ID......
  • RTC-RTC软件校准思路
    首先想实现RTC校准,必须要借助上面的寄存器。通过上面的寄存器可以实现的校准误差对应为0-121ppm,相当于每30天跑快的秒数是0-314秒。但是这里需要注意的一个关键问题是,根据上面寄存器的描述,这个寄存器的值表示再每2的20次方个时钟脉冲中有多少个被跳过,用来减慢RTC时钟。所以通过......
  • 1、TCP/IP模型有哪几层?
    应用层应用层只需关注给用户提供的功能,当两个设备需要进行通讯的时候,只需要把要发送的数据发送给传输层即可。传输层传输层是为应用层提供网络支持的,传输层有两个传输协议:TCP和UDPTCP:大部分应用用的正是TCP协议,如HTTP。相对于UDP协议,TCP协议多了很多特性:流量控制、超时重传......
  • 【AGC】接入分发和运营分析相关问题
     【关键字】AGC、分发分析、运营分析 【问题描述】开发者反馈在应用中接入AGC分发分析、运营分析、事件分析时遇到了一些问题。具体如下所述:1、事件分析里面的埋点事件参数和参数值是否有数量限制。2、埋点统计是否是收费项目,是的话是否有免费额度。3、分析服务中是否有a......
  • AtCoder Beginner Contest 301 F Anti-DDoS
    洛谷传送门AtCoder传送门考虑分类计数,讨论“没有DD”、“有DD无o”、“有DDo无S”三种情况。没有DD,枚举有几种大写字母出现过;剩下两种情况,考虑设\(f_{i,0/1}\)分别表示两种情况的方案数。\(f_{i,0}\)可以从\(f_{i-1,0}\)填大写字母转移,也可以枚举第一个出现两......
  • 埃斯顿 伺服驱动器 方案 C源码 埃斯顿 伺服驱动器 方案 C源码 可直 伺服驱动方案
    埃斯顿伺服驱动器方案C源码埃斯顿伺服驱动器方案C源码可直伺服驱动方案源码资料C语言源代码,资料齐全可直接生产!2500线省线式编码器,17位增量编码器,20位绝对值编码器!标配CANopen、高精度运动控制,高速总线通讯,可靠性好,性价比高。资料网上花3千买的,需要的直接联系。埃......
  • 汇川频器md380量产方案,包含原理图,pcb图,矢量源码。 拿来
    汇川频器md380量产方案,包含原理图,pcb图,矢量源码。拿来就用!量产参考,学习提高,必备利器。ID:195612600074192......
  • 打印ASCII码
    【题目描述】输入一个除空格以外的可见字符,输出其ASCII码。【输入】一个除空格以外的可见字符。【输出】一个十进制整数,即该字符的ASCII码。【输入样例】A【输出样例】65 while1:ch=input("请输入一个字符:")print(ord(ch))#print()......
  • Commonly Used Prompts for Reducing Duplicate Rate
    Simplerewrite:Tryhardtorewritethefollowingcontent,makesurethemeaningisthesameastheoriginalmeaningbutjusttrytousedifferentwordsespeciallyformalwords:Rewriteabstractorsomecopiedtextsfromapaper:Rewritethefollowing......