C# 使用 HttpClient调HTTP请求

实现HttpClient单例模式,发送HTTP请求。

    public class HttpClientHelper
    {
        private static readonly object LockObj = new object();
        private static HttpClient client = null;
        public HttpClientHelper()
        {
            CreateInstance();
        }
        public static HttpClient CreateInstance()
        {

            if (client == null)
            {
                lock (LockObj)
                {
                    if (client == null)
                    {
                        client = new HttpClient();
                    }
                }
            }
            return client;
        }
        public async Task<string> PostAsync(string url, string strJson)//post异步请求方法
        {
            try
            {
                HttpContent content = new StringContent(strJson);
                content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                //由HttpClient发出异步Post请求
                HttpResponseMessage res = await client.PostAsync(url, content);
                if (res.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    string str = res.Content.ReadAsStringAsync().Result;
                    return str;
                }
                else
                    return null;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        public string Post(string url, string strJson)//post同步请求方法
        {
            try
            {
                HttpContent content = new StringContent(strJson);
                content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                //client.DefaultRequestHeaders.Connection.Add("keep-alive");
                //由HttpClient发出Post请求
                Task<HttpResponseMessage> res = client.PostAsync(url, content);
                if (res.Result.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    string str = res.Result.Content.ReadAsStringAsync().Result;
                    return str;
                }
                else
                    return null;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        public static string HttpClientGet(string url)
        {
            try
            {
                var responseString = client.GetStringAsync(url);
                return responseString.Result;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

    }

使用WebRequest发送同步POST请求:

 public string HttpClientPost(string url, string strJson)//post同步请求方法
        {
            try
            {
                string responseStr = string.Empty;

                WebRequest request = WebRequest.Create(url);
                request.Method = "Post";
                request.ContentType = "application/json";

                byte[] requestData = System.Text.Encoding.UTF8.GetBytes(strJson);
                request.ContentLength = requestData.Length;

                Stream newStream = request.GetRequestStream();
                newStream.Write(requestData, 0, requestData.Length);
                newStream.Close();

                var response = request.GetResponse();
                Stream ReceiveStream = response.GetResponseStream();
                using (StreamReader stream = new StreamReader(ReceiveStream, Encoding.UTF8))
                {
                    responseStr = stream.ReadToEnd();
                }

                return responseStr;
            }
            catch (Exception ex)
            {
                ToolFunction.ErrLog(ex.Source, ex.StackTrace + "---" + ex.Message);
                return string.Empty;
            
}

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值