C# HttpWebRequest httpclient HttpClientFactory

 

HttpWebRequest

 

     public static class HttpHelper
    {
        private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";

        private static Encoding requestEncoding = Encoding.UTF8;

        public static bool HttpGet(string url, out string HttpWebResponseString, int timeout)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }
            HttpWebResponseString = "";
            try
            {
                HttpWebRequest httpWebRequest = WebRequest.Create(url) as HttpWebRequest;
                httpWebRequest.Method = "GET";
                httpWebRequest.ContentType = "application/x-www-form-urlencoded";
                httpWebRequest.UserAgent = DefaultUserAgent;
                httpWebRequest.Timeout = timeout;
                HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
                HttpWebResponseString = ReadHttpWebResponse(httpWebResponse);
                return true;
            }
            catch (Exception ex)
            {
                HttpWebResponseString = ex.ToString();
                return false;
            }
        }

        public static bool HttpPost(string url, byte[] Data, out string HttpWebResponseString, int timeout)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }
            HttpWebResponseString = "";
            HttpWebRequest httpWebRequest = null;
            Stream stream = null;
            try
            {
                httpWebRequest = (WebRequest.Create(url) as HttpWebRequest);
                httpWebRequest.Method = "POST";
                httpWebRequest.ContentType = "application/x-www-form-urlencoded";
                httpWebRequest.UserAgent = DefaultUserAgent;
                httpWebRequest.Timeout = timeout;
                if (Data != null)
                {
                    requestEncoding.GetString(Data);
                    stream = httpWebRequest.GetRequestStream();
                    stream.Write(Data, 0, Data.Length);
                }
                HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
                HttpWebResponseString = ReadHttpWebResponse(httpWebResponse);
                return true;
            }
            catch (Exception ex)
            {
                HttpWebResponseString = ex.ToString();
                return false;
            }
            finally
            {
                stream?.Close();
            }
        }

        /// <summary>
        /// 指定Post地址使用Get 方式获取全部字符串
        /// </summary>
        /// <param name="url">请求后台地址</param>
        /// <returns></returns>
        public static string Post(string url, Dictionary<string, string> dic)
        {
            string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            #region 添加Post 参数
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            return result;
        }

        public static string HttpPost(string url, IDictionary<string, string> parameters, string charset)
        {

            //StreamWriter sw = new StreamWriter(Application.StartupPath + @"/SyncUrl.log", true, System.Text.Encoding.GetEncoding("gb2312"));
            //sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + @"  "  + url);
            //sw.Close(); sw.Dispose();

            HttpWebRequest req = GetWebRequest(url, "POST");
            req.ContentType = "application/json;charset=" + charset;
            
            string p = BuildQuery(parameters, charset);
            byte[] postData = Encoding.GetEncoding(charset).GetBytes(p);
            Stream reqStream = req.GetRequestStream();
            reqStream.Write(postData, 0, postData.Length);
            reqStream.Close();
            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
            return GetResponseAsString(rsp, Encoding.UTF8);
        }

        public static string HttpPost(string url, IDictionary<string, string> parameters, string charset,string contentType)
        {

          

            HttpWebRequest req = GetWebRequest(url, "POST");
            req.ContentType = contentType;

            string p = BuildQuery(parameters, charset);
            byte[] postData = Encoding.GetEncoding(charset).GetBytes(p);
            Stream reqStream = req.GetRequestStream();
            reqStream.Write(postData, 0, postData.Length);
            reqStream.Close();
            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
            return GetResponseAsString(rsp, Encoding.UTF8);
        }

        public static string Post(string url, IDictionary<string, string> parameters, string data, string apiToken = null)
        {
            if (parameters != null && parameters.Count > 0)
            {
                if (url.Contains("?"))
                {
                    url = url + "&" + BuildQuery(parameters);
                }
                else
                {
                    url = url + "?" + BuildQuery(parameters);
                }
            }

            HttpWebRequest req = GetWebRequest(url, "POST");
            req.ContentType = "application/json;charset=utf-8";
            if (!string.IsNullOrEmpty(apiToken))
            {
                req.Headers.Add("apiToken", apiToken);
            }

            byte[] postData = Encoding.UTF8.GetBytes(data);
            System.IO.Stream reqStream = req.GetRequestStream();
            reqStream.Write(postData, 0, postData.Length);
            reqStream.Close();

            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
            return GetResponseAsString(rsp, Encoding.UTF8);
        }


        public static string sendPost(string url, string json)
        {
            System.IO.Stream stream = null;
            StreamReader reader = null;
            try
            {
                Encoding encoding = Encoding.UTF8;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.Accept = "text/html, application/xhtml+xml, */*";
                request.ContentType = "application/json";


                byte[] buffer = encoding.GetBytes(json);
                request.ContentLength = buffer.Length;
                request.GetRequestStream().Write(buffer, 0, buffer.Length);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                using (reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                { return reader.ReadToEnd(); }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return "{\"FStatus\":0,\"FMsg\":'" + ex.Message + "'}";
            }
            finally
            {
                if (stream != null) stream.Close();
                if (reader != null) reader.Close();
            }
            return null;
        }

        private static HttpWebRequest GetWebRequest(string url, string method)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.ServicePoint.Expect100Continue = false;
            req.Method = method;
            req.KeepAlive = true;
            req.UserAgent = "SEASHOP";
            req.Timeout = 300000;
            return req;
        }

        /// <summary>
        /// 把响应流转换为文本。
        /// </summary>
        /// <param name="rsp">响应流对象</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>响应文本</returns>
        public static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
        {
            StringBuilder result = new StringBuilder();
            Stream stream = null;
            StreamReader reader = null;

            try
            {
                // 以字符流的方式读取HTTP响应
                stream = rsp.GetResponseStream();
                reader = new StreamReader(stream, encoding);

                // 按字符读取并写入字符串缓冲
                int ch = -1;
                while ((ch = reader.Read()) > -1)
                {
                    // 过滤结束符
                    char c = (char)ch;
                    if (c != '\0')
                    {
                        result.Append(c);
                    }
                }
            }
            finally
            {
                // 释放资源
                if (reader != null) reader.Close();
                if (stream != null) stream.Close();
                if (rsp != null) rsp.Close();
            }

            return result.ToString();
        }

        /// <summary>
        /// 组装普通文本请求参数。
        /// </summary>
        /// <param name="parameters">Key-Value形式请求参数字典</param>
        /// <returns>URL编码后的请求数据</returns>
        public static string BuildQuery(IDictionary<string, string> parameters, string charset)
        {
            StringBuilder postData = new StringBuilder();
            bool hasParam = false;

            IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
            while (dem.MoveNext())
            {
                string name = dem.Current.Key;
                string value = dem.Current.Value;
                // 忽略参数名或参数值为空的参数
                if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value))
                {
                    if (hasParam)
                    {
                        postData.Append("&");
                    }

                    postData.Append(name);
                    postData.Append("=");

                    string encodedValue = HttpUtility.UrlEncode(value, Encoding.GetEncoding(charset));

                    postData.Append(encodedValue);
                    hasParam = true;
                }
            }

            return postData.ToString();
        }

        public static string ReadHttpWebResponse(HttpWebResponse HttpWebResponse)
        {
            Stream stream = null;
            StreamReader streamReader = null;
#pragma warning disable CS0219 // 变量“text”已被赋值,但从未使用过它的值
            string text = null;
#pragma warning restore CS0219 // 变量“text”已被赋值,但从未使用过它的值
            try
            {
                stream = HttpWebResponse.GetResponseStream();
                streamReader = new StreamReader(stream, Encoding.GetEncoding("utf-8"));
                return streamReader.ReadToEnd();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                streamReader?.Close();
                stream?.Close();
                HttpWebResponse?.Close();
            }
        }

        public static string BuildQuery(IDictionary<string, string> parameters)
        {
            StringBuilder postData = new StringBuilder();
            bool hasParam = false;

            IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
            while (dem.MoveNext())
            {
                string name = dem.Current.Key;
                string value = dem.Current.Value;
                // 忽略参数名或参数值为空的参数
                if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value))
                {
                    if (hasParam)
                    {
                        postData.Append("&");
                    }

                    postData.Append(name);
                    postData.Append("=");
                    postData.Append(HttpUtility.UrlEncode(value, Encoding.UTF8));
                    hasParam = true;
                }
            }

            return postData.ToString();
        }
    }
HttpWebRequest

 

httpclient post get

 

using ICSharpCode.SharpZipLib.GZip;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

/// <summary>
/// 基于HttpClient封装的请求类
/// </summary>
public class HttpRequest
{
    /// <summary>
    /// 使用post方法异步请求
    /// </summary>
    /// <param name="url">目标链接</param>
    /// <param name="json">发送的参数字符串,只能用json</param>
    /// <returns>返回的字符串</returns>
    public static async Task<string> PostAsyncJson(string url, string json)
    {
        HttpClient client = new HttpClient();
        HttpContent content = new StringContent(json);
        content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
        HttpResponseMessage response = await client.PostAsync(url, content);
        response.EnsureSuccessStatusCode();
        string responseBody = await response.Content.ReadAsStringAsync();
        return responseBody;
    }

    /// <summary>
    /// 使用post方法异步请求
    /// </summary>
    /// <param name="url">目标链接</param>
    /// <param name="data">发送的参数字符串</param>
    /// <returns>返回的字符串</returns>
    public static async Task<string> PostAsync(string url, string data, Dictionary<string, string> header = null, bool Gzip = false)
    {
        HttpClient client = new HttpClient(new HttpClientHandler() { UseCookies = false });
        HttpContent content = new StringContent(data);
        if (header != null)
        {
            client.DefaultRequestHeaders.Clear();
            foreach (var item in header)
            {
                client.DefaultRequestHeaders.Add(item.Key, item.Value);
            }
        }
        HttpResponseMessage response = await client.PostAsync(url, content);
        response.EnsureSuccessStatusCode();
        string responseBody = "";
        if (Gzip)
        {
            GZipInputStream inputStream = new GZipInputStream(await response.Content.ReadAsStreamAsync());
            responseBody = new StreamReader(inputStream).ReadToEnd();
        }
        else
        {
            responseBody = await response.Content.ReadAsStringAsync();

        }
        return responseBody;
    }

    /// <summary>
    /// 使用get方法异步请求
    /// </summary>
    /// <param name="url">目标链接</param>
    /// <returns>返回的字符串</returns>
    public static async Task<string> GetAsync(string url, Dictionary<string, string> header = null, bool Gzip = false)
    {

        HttpClient client = new HttpClient(new HttpClientHandler() { UseCookies = false });
        if (header != null)
        {
            client.DefaultRequestHeaders.Clear();
            foreach (var item in header)
            {
                client.DefaultRequestHeaders.Add(item.Key, item.Value);
            }
        }
        HttpResponseMessage response = await client.GetAsync(url);
        response.EnsureSuccessStatusCode();//用来抛异常的
        string responseBody = "";
        if (Gzip)
        {
            GZipInputStream inputStream = new GZipInputStream(await response.Content.ReadAsStreamAsync());
            responseBody = new StreamReader(inputStream).ReadToEnd();
        }
        else
        {
            responseBody = await response.Content.ReadAsStringAsync();

        }
        return responseBody;
    }

    /// <summary>
    /// 使用post返回异步请求直接返回对象
    /// </summary>
    /// <typeparam name="T">返回对象类型</typeparam>
    /// <typeparam name="T2">请求对象类型</typeparam>
    /// <param name="url">请求链接</param>
    /// <param name="obj">请求对象数据</param>
    /// <returns>请求返回的目标对象</returns>
    public static async Task<T> PostObjectAsync<T, T2>(string url, T2 obj)
    {
        String json = JsonConvert.SerializeObject(obj);
        string responseBody = await PostAsyncJson(url, json); //请求当前账户的信息
        return JsonConvert.DeserializeObject<T>(responseBody);//把收到的字符串序列化
    }

    /// <summary>
    /// 使用Get返回异步请求直接返回对象
    /// </summary>
    /// <typeparam name="T">请求对象类型</typeparam>
    /// <param name="url">请求链接</param>
    /// <returns>返回请求的对象</returns>
    public static async Task<T> GetObjectAsync<T>(string url)
    {
        string responseBody = await GetAsync(url); //请求当前账户的信息
        return JsonConvert.DeserializeObject<T>(responseBody);//把收到的字符串序列化
    }
}
HttpClient

 

HttpClientFactory

 https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/http-requests?view=aspnetcore-5.0

https://docs.microsoft.com/zh-cn/dotnet/api/system.net.http.multipartformdatacontent.add?view=net-5.0

    public class HttpClientFactoryService
    {
        /// <summary>
        /// 注入http请求
        /// </summary>
        private readonly IHttpClientFactory _httpClientFactory;

        public HttpClientFactoryService(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }

        // <summary>
        // Get请求数据
        // <para>最终以url参数的方式提交</para>
        // </summary>
        // <param name = "requestUri" > 例如 / api / Files / UploadFile </ param >
        // <param name="parameters">参数字典,可为空</param>
        // <returns></returns>
        public async Task<BaseResponse<T>> GetAsync<T>(string requestUri, Dictionary<string, string> parameters = null ,  string token = null)
        {
            BaseResponse<T> result = new BaseResponse<T>();
            try
            {
                //var request = new HttpRequestMessage(HttpMethod.Get, "http://***:***/");
                //var str12 = client.GetFromJsonAsync<BaseResponse<T>>("http://***:***//").Result;
                //return result;

                //拼接地址
                if (parameters != null)
                {
                    var strParam = string.Join("&", parameters.Select(o => o.Key + "=" + o.Value));
                    requestUri = string.Concat(requestUri, '?', strParam);
                }

                var request = new HttpRequestMessage(HttpMethod.Get, requestUri);
                //request.Headers.Add("Accept", "application/vnd.github.v3+json");
                //request.Headers.Add("User-Agent", "HttpClientFactory-Sample");

                //从工厂获取请求对象   声明自己创建哪一个httpClient客户端
                var client = _httpClientFactory.CreateClient();
                //client.BaseAddress = new Uri("http://***:***/");
                //添加请求头
                if (!string.IsNullOrWhiteSpace(token))
                {
                    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
                }

                var response = client.SendAsync(request).Result;

                if (response.IsSuccessStatusCode)
                {
                    var strReadAsync = await response.Content.ReadAsStringAsync();
                    result = Newtonsoft.Json.JsonConvert.DeserializeObject<BaseResponse<T>>(strReadAsync);

                    //using var responseStream = await response.Content.ReadAsStreamAsync();
                    //result = await JsonSerializer.DeserializeAsync<BaseResponse<T>>(responseStream);
                }
                else
                {
                    result.Status = 500;
                    result.Message = "请求接口失败!";
                }
            }
            catch (Exception ex)
            {
                var exMsg = ex.Message != null ? ex.Message : ex.StackTrace;

                result.Status = 500;
                result.Message = $"请求接口异常!{exMsg}";

                LogUtility.Info(exMsg);
            }

            return await Task.FromResult(result);

        }

        /// <summary>
        /// Post请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="requestUri">地址</param>
        /// <param name="parameters">参数</param>
        /// <param name="token"></param>
        /// <returns></returns>
        public async Task<BaseResponse<T>> PostAsync<T>(string requestUri, object parameters = null, string token = null)
        {
            BaseResponse<T> result = new BaseResponse<T>();
            try
            {
                var request = new HttpRequestMessage(HttpMethod.Post, requestUri);

                if (parameters!= null)
                {
                    var todoItemJson = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(parameters), Encoding.UTF8, "application/json");
                    request.Content = todoItemJson;
                }
                
                var client = _httpClientFactory.CreateClient();
                //client.BaseAddress = new Uri("http://***:***/");
                //添加请求头
                if (!string.IsNullOrWhiteSpace(token))
                {
                    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
                }
                var response = client.SendAsync(request).Result;

                //using var response = client.PostAsync(requestUri, todoItemJson).Result;

                response.EnsureSuccessStatusCode();

                if (response.IsSuccessStatusCode)
                {
                    var strReadAsync = await response.Content.ReadAsStringAsync();
                    result = Newtonsoft.Json.JsonConvert.DeserializeObject<BaseResponse<T>>(strReadAsync);

                    //using var responseStream = await response.Content.ReadAsStreamAsync();
                    //result = await JsonSerializer.DeserializeAsync<BaseResponse<T>>(responseStream);
                }
                else
                {
                    result.Status = 500;
                    result.Message = "请求接口失败!";
                }

            }
            catch (Exception ex)
            {
                var strEx = ex.Message;
                result.Status = 500;
                result.Message = "请求接口异常!";
            }

            return await Task.FromResult(result);

        }

    }
HttpClientFactory

替换 :var response = await client.SendAsync(request).ConfigureAwait(false);

 response.EnsureSuccessStatusCode(); //错误抛异常

 

上传文件并附带其他参数

using (HttpClient client = new HttpClient())
{
    var content = new MultipartFormDataContent();
    //添加字符串参数,参数名为qq
    content.Add(new StringContent("123456"), "qq");

    string path = Path.Combine(System.Environment.CurrentDirectory, "1.png");
    //添加文件参数,参数名为files,文件名为123.png
    content.Add(new ByteArrayContent(System.IO.File.ReadAllBytes(path)), "file", "123.png");

    var requestUri = "http://192.168.1.108:56852/api/Test/SaveFile";
    var result = client.PostAsync(requestUri, content).Result.Content.ReadAsStringAsync().Result;

    Console.WriteLine(result);
}
添加文件

 

        /// <summary>
        /// 获取文件集合对应的ByteArrayContent集合
        /// </summary>
        /// <param name="files"></param>
        /// <returns></returns>
        private List<ByteArrayContent> GetFileByteArrayContent(HashSet<string> files)
        {
            List<ByteArrayContent> list = new List<ByteArrayContent>();
            foreach (var file in files)
            {
                var fileContent = new ByteArrayContent(File.ReadAllBytes(file));
                fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = Path.GetFileName(file)
                };
                list.Add(fileContent);
            }
            return list;
        }
        /// <summary>
        /// 获取键值集合对应的ByteArrayContent集合
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        private List<ByteArrayContent> GetFormDataByteArrayContent(NameValueCollection collection)
        {
            List<ByteArrayContent> list = new List<ByteArrayContent>();
            foreach (var key in collection.AllKeys)
            {
                var dataContent = new ByteArrayContent(Encoding.UTF8.GetBytes(collection[key]));
                dataContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    Name = key
                };
                list.Add(dataContent);
            }
            return list;
        }
加参数

 

            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/" + this.cmbResponseContentType.Text.ToLower()));//设定要响应的数据格式
                using (var content = new MultipartFormDataContent())//表明是通过multipart/form-data的方式上传数据
                {
                    var formDatas = this.GetFormDataByteArrayContent(this.GetNameValueCollection(this.gv_FormData));//获取键值集合对应的ByteArrayContent集合
                    var files = this.GetFileByteArrayContent(this.GetHashSet(this.gv_File));//获取文件集合对应的ByteArrayContent集合
                    Action<List<ByteArrayContent>> act = (dataContents) =>
                    {//声明一个委托,该委托的作用就是将ByteArrayContent集合加入到MultipartFormDataContent中
                        foreach (var byteArrayContent in dataContents)
                        {
                            content.Add(byteArrayContent);
                        }
                    };
                    act(formDatas);//执行act
                    act(files);//执行act
                    try
                    {
                        var result = client.PostAsync(this.txtUrl.Text, content).Result;//post请求
                        this.txtResponse.Text = result.Content.ReadAsStringAsync().Result;//将响应结果显示在文本框内
                    }
                    catch (Exception ex)
                    {
                        this.txtResponse.Text = ex.ToString();//将异常信息显示在文本框内
                    }
                }
            }
HttpClient

 

 

application/x-www-form-urlencoded(大多数请求可用:eg:'name=Denzel&age=18')
multipart/form-data(文件上传,这次重点说)
application/json(json格式对象,eg:{'name':'Denzel','age':'18'})
text/xml(现在用的很少了,发送xml格式文件或流,webservice请求用的较多)



string boundary = string.Format("----WebKitFormBoundary{0}",DateTime.Now.Ticks.ToString("x"));
MultipartFormDataContent content = new MultipartFormDataContent(boundary);

content.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");

content.Add(new StreamContent(fStream, (int)fStream.Length), "file", fileName);
View Code

 

 

 https://www.cnblogs.com/chenxi001/p/12203731.html

https://www.cjavapy.com/article/527/

posted @ 2021-08-18 12:18  bxzjzg  阅读(212)  评论(0编辑  收藏  举报