在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
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(); } }
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);//把收到的字符串序列化 } }
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.IsSuccessStatus |
请发表评论