.NET Http请求
声明:本代码只是我使用的网络请求方式的封装,大家如果有其他的可以一起讨论讨论。
本代码可以在.NET 与.NET CORE的平台下无须做任何改动(除非手动加一些必要的引用,resharper会有提示.)即可使用。
using System; using System.IO; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; namespace FrameWork.Common.Web { public class HttpHelper { /// <summary> /// 发起一个HTTP请求(以POST同步方式) /// </summary> /// <param name="url">请求地址</param> /// <param name="param">参数:json格式字符串</param> public static string HttpPost(string url, string param = "") { var request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/json"; request.Accept = "*/*"; request.Timeout = 10000; request.AllowAutoRedirect = false; StreamWriter requestStream = null; WebResponse response = null; string responseStr = null; try { requestStream = new StreamWriter(request.GetRequestStream()); requestStream.Write(param); requestStream.Close(); response = request.GetResponse(); if (response != null) { var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); responseStr = reader.ReadToEnd(); reader.Close(); } } catch (Exception e) { throw e; } finally { request = null; requestStream = null; response = null; } return responseStr; } /// <summary> /// get请求,同步方式 /// </summary> public static string HttpGet(string url, string postDataStr) { var request = (HttpWebRequest)WebRequest.Create(url + (postDataStr == "" ? "" : "?") + postDataStr); request.Method = "GET"; request.ContentType = "text/html;charset=UTF-8"; var response = (HttpWebResponse)request.GetResponse(); var myResponseStream = response.GetResponseStream(); var myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); var retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); return retString; } /// <summary> /// 发送短信,异步请求
/// </summary> /// <param name="url">请求地址</param> /// <param name="jsonString">json字符串,手机号和短信内容必填</param> public static void SendMessage(string url, string jsonString) { var client = new HttpClient(); HttpContent httpContext = new StringContent(jsonString, Encoding.UTF8); httpContext.Headers.ContentType = new MediaTypeHeaderValue("application/json"); //await异步等待回应 client.PostAsync(url, httpContext).ContinueWith(t => { // Get HTTP response from completed task. var response = t.Result; // Check that response was successful or throw exception response.EnsureSuccessStatusCode(); // Read response asynchronously as JsonValue and write out top facts for each country response.Content.ReadAsStringAsync().ContinueWith( readTask => { Console.WriteLine(readTask.Result + " time:==>" + DateTime.Now);// 感谢评论中指出的问题。这里可以改成记录到数据库或者记录到本地文件,再或者改成异步返回的方法。 }); }); } } }