using System.Net; using System.Net.Http.Headers; using System.Net.Http; using System.Text; using DS.Module.Core.Extensions; using System.Security.Policy; namespace DS.Module.Core.Helpers; /// /// 请求帮助类 /// public class RequestHelper { public static string Post(string postData, string Url,int timeout = 60000) { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(Url); req.Method = "POST"; req.Timeout = timeout; //设置请求超时时间,单位为毫秒 req.ContentType = "application/json"; byte[] data = Encoding.UTF8.GetBytes(postData); req.ContentLength = data.Length; using (Stream reqStream = req.GetRequestStream()) { reqStream.Write(data, 0, data.Length); reqStream.Close(); } HttpWebResponse response = (HttpWebResponse)req.GetResponse(); Stream stream = response.GetResponseStream(); Encoding encode = Encoding.UTF8; StreamReader reader = new StreamReader(stream, encode); string content = reader.ReadToEnd(); stream.Close(); reader.Close(); return content; } public static string Get(string Url) { string content = String.Empty; HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(Url); req.Method = "GET"; req.ContentType = "text/html;charset=UTF-8"; HttpWebResponse response = (HttpWebResponse)req.GetResponse(); Stream stream = response.GetResponseStream(); Encoding encode = Encoding.UTF8; StreamReader reader = new StreamReader(stream, encode); content = reader.ReadToEnd(); stream.Close(); reader.Close(); return content; } public static string GetResponseByGet(string url) { string result = string.Empty; using (HttpClient httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.Accept.Add( new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = httpClient.GetAsync(url).Result; //statusCode = response.StatusCode.ToString(); if (response.IsSuccessStatusCode) { result = response.Content.ReadAsStringAsync().Result; } } return result; } /// /// http post请求 /// /// 地址 /// 入参 /// /// 头信息 /// /// /// , string token ="", Dictionary headers = null public static async Task PostAsyncNoHeaders(string url, string parameter) { using (var client = new HttpClient()) { //var data = new StringContent("param1=value1¶m2=value2", Encoding.UTF8, "application/x-www-form-urlencoded"); var data = new StringContent(parameter, Encoding.UTF8, "application/x-www-form-urlencoded"); //_logger.LogWarning($"data:{data.ToJsonString()};parameter:{parameter}"); // 添加header参数 //client.DefaultRequestHeaders.Add("Authorization", "Bearer your_token_here"); //foreach (var header in headers) //{ // client.DefaultRequestHeaders.Add(header.Key, header.Value); //} //_logger.LogWarning($"header:{client.DefaultRequestHeaders.ToJsonString()}"); try { var response = await client.PostAsync(url, data); response.EnsureSuccessStatusCode(); var responseBody = await response.Content.ReadAsStringAsync(); return responseBody; } catch (HttpRequestException e) { throw new Exception(e.Message); } } } /// /// http post请求 /// /// 地址 /// 入参 /// 头信息 /// /// /// , string token ="", Dictionary headers = null public static async Task PostAsyncWithHeaders(string url, string parameter,Dictionary headers) { using (var client = new HttpClient()) { //var data = new StringContent("param1=value1¶m2=value2", Encoding.UTF8, "application/x-www-form-urlencoded"); var data = new StringContent(parameter, Encoding.UTF8, "application/json"); //_logger.LogWarning($"data:{data.ToJsonString()};parameter:{parameter}"); // 添加header参数 //client.DefaultRequestHeaders.Add("Authorization", "Bearer your_token_here"); foreach (var header in headers) { client.DefaultRequestHeaders.Add(header.Key, header.Value); } //_logger.LogWarning($"header:{client.DefaultRequestHeaders.ToJsonString()}"); try { var response = await client.PostAsync(url, data); //response.EnsureSuccessStatusCode(); var responseBody = await response.Content.ReadAsStringAsync(); return responseBody; } catch (HttpRequestException e) { throw new Exception(e.Message); } } } /// /// http post请求 /// /// 地址 /// 入参 /// /// 头信息 /// /// /// , string token ="", Dictionary headers = null public static async Task PostJsonAsyncNoHeaders(string url, string parameter) { using (var client = new HttpClient()) { //var data = new StringContent("param1=value1¶m2=value2", Encoding.UTF8, "application/x-www-form-urlencoded"); var data = new StringContent(parameter, Encoding.UTF8, "application/json"); //_logger.LogWarning($"data:{data.ToJsonString()};parameter:{parameter}"); // 添加header参数 //client.DefaultRequestHeaders.Add("Authorization", "Bearer your_token_here"); //foreach (var header in headers) //{ // client.DefaultRequestHeaders.Add(header.Key, header.Value); //} //_logger.LogWarning($"header:{client.DefaultRequestHeaders.ToJsonString()}"); try { var response = await client.PostAsync(url, data); response.EnsureSuccessStatusCode(); var responseBody = await response.Content.ReadAsStringAsync(); return responseBody; } catch (HttpRequestException e) { throw new Exception(e.Message); } } } public static async Task PostJosnAsyncByToken(string url, string parameter,string token) { using (var client = new HttpClient()) { //var data = new StringContent("param1=value1¶m2=value2", Encoding.UTF8, "application/x-www-form-urlencoded"); var data = new StringContent(parameter, Encoding.UTF8, "application/json"); //_logger.LogWarning($"data:{data.ToJsonString()};parameter:{parameter}"); //添加header参数 client.DefaultRequestHeaders.Add("Authorization", "Bearer "+ token); //foreach (var header in headers) //{ // client.DefaultRequestHeaders.Add(header.Key, header.Value); //} //_logger.LogWarning($"header:{client.DefaultRequestHeaders.ToJsonString()}"); try { var response = await client.PostAsync(url, data); response.EnsureSuccessStatusCode(); var responseBody = await response.Content.ReadAsStringAsync(); return responseBody; } catch (HttpRequestException e) { throw new Exception(e.Message); } } } /// /// http异步请求 /// /// url /// 请求方法 GET、POST /// 回调函数 /// 回传对象 /// post数据 public static void HttpAsyncRequest(string url, string reqMethod, AsyRequetCallback callback, object ob = null, string postData = "") { Stream requestStream = null; try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.ContentType = "application/x-www-form-urlencoded"; request.Method = reqMethod; if (reqMethod.ToUpper() == "POST") { byte[] bytes = Encoding.UTF8.GetBytes(postData); request.ContentLength = bytes.Length; requestStream = request.GetRequestStream(); requestStream.Write(bytes, 0, bytes.Length); } //开始调用异步请求 //AsyResultTag 是自定义类 用于传递调用时信息 其中HttpWebRequest 是必须传递对象。 //因为回调需要用HttpWebRequest来获取HttpWebResponse request.BeginGetResponse(new AsyncCallback(HttpCallback), new AsyResultTag() { obj = ob, callback = callback, req = request }); } catch (Exception ex) { throw ex; } finally { if (requestStream != null) { requestStream.Close(); } } } /// /// http请求回调 由.net内部调用 参数必须为IAsyncResult /// /// http回调时回传对象 private static void HttpCallback(IAsyncResult asynchronousResult) { int statusCode = 0; string retString = ""; AsyResultTag tag = new AsyResultTag(); WebException webEx = null; try { //获取请求时传递的对象 tag = asynchronousResult.AsyncState as AsyResultTag; HttpWebRequest req = tag.req; //获取异步返回的http结果 HttpWebResponse response = req.EndGetResponse(asynchronousResult) as HttpWebResponse; Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); statusCode = ((int)response.StatusCode); } catch (WebException ex) { if ((HttpWebResponse)ex.Response != null) { statusCode = ((int)((HttpWebResponse)ex.Response).StatusCode); } webEx = ex; } //调用外部回调 即最外层的回调 tag.callback(tag.obj, retString, statusCode, webEx); } /// /// 异步请求回调委托 /// /// 回传对象 /// http响应结果 /// http状态码 /// 异常 public delegate void AsyRequetCallback(object asyObj, string respStr, int statusCode, WebException webEx); /// /// 异步返回对象 /// public class AsyResultTag { /// /// 回传对象 /// public object obj { get; set; } /// /// 当前httpRequest请求实例 /// public HttpWebRequest req { get; set; } /// /// 回调函数委托 /// public AsyRequetCallback callback { get; set; } } }