.Net中的Rest风格Http请求同步异步封装Helper类,带Auth
其实这个Helper也是我从网上其他地方扒下来的,然后做了一些修改。
因为扒下来也好几天了,所以从哪里扒下来的已经不是特别记得了。
直接上代码吧。
简单的调用就好。
异步版本的借鉴了这里,异步方法没有做测试,但应该能用。不能用可以来找我,我再改一下、

1 /// <summary> 2 /// 基于Rest封装的Http请求 3 /// </summary> 4 public class RestClientHelper 5 { 6 const string GET = "GET"; 7 const string POST = "POST"; 8 const string PUT = "PUT"; 9 const string DELETE = "DELETE"; 10 const string AUTH = "Authorization"; 11 const string APP_JSON = "application/json"; 12 const string UTF_8 = "UTF-8"; 13 /// <summary> 14 /// 超时时常(毫秒) 15 /// </summary> 16 public int TimeOut = 100; 17 public RestClientHelper() 18 { 19 20 } 21 public RestClientHelper(int timeOut) 22 { 23 TimeOut = timeOut; 24 } 25 #region Get请求 26 public string Get(string uri, string auth = null) 27 => HttpReq(GetHttpWebRequest(uri, GET, null, auth)); 28 29 public async Task<string> GetAsync(string uri, string auth = null) 30 => await HttpReqAsync(GetHttpWebRequest(uri, GET, null, auth)); 31 32 #endregion 33 34 #region Post请求 35 public string Post(string uri, string data, string auth = null) 36 => HttpReqWithAuth(uri, POST, data, auth); 37 38 public async Task<string> PostAsync(string uri, string data, string auth = null) 39 => await HttpReqWithAuthAsync(uri, POST, data, auth); 40 #endregion 41 42 #region Put请求 43 public string Put(string uri, string data, string auth = null) 44 => HttpReqWithAuth(uri, PUT, data, auth); 45 46 public async Task<string> PutAsync(string uri, string data, string auth = null) 47 => await HttpReqWithAuthAsync(uri, PUT, data, auth); 48 #endregion 49 50 #region Delete请求 51 public string Delete(string uri, string data, string auth = null) 52 => HttpReqWithAuth(uri, DELETE, data, auth); 53 54 public async Task<string> DeleteAsync(string uri, string data, string auth = null) 55 => await HttpReqWithAuthAsync(uri, DELETE, data, auth); 56 #endregion 57 58 #region 工具类 59 /// <summary> 60 /// 带有Auth的请求 61 /// </summary> 62 /// <param name="uri"></param> 63 /// <param name="methodType"></param> 64 /// <param name="data"></param> 65 /// <param name="auth"></param> 66 /// <param name="ContentType"></param> 67 /// <param name="encoding"></param> 68 /// <returns></returns> 69 private string HttpReqWithAuth(string uri, string methodType, string data, string auth, string ContentType = APP_JSON, string encoding = UTF_8) 70 { 71 byte[] buf = Encoding.GetEncoding(encoding).GetBytes(data); 72 HttpWebRequest myRequest = GetHttpWebRequest(uri, methodType, buf, auth, ContentType, encoding); 73 //发送请求 74 using (Stream stream = myRequest.GetRequestStream()) 75 { 76 stream.Write(buf, 0, buf.Length); 77 } 78 return HttpReq(myRequest); 79 } 80 /// <summary> 81 /// 不带请求头的直接发送请求 82 /// </summary> 83 /// <param name="myRequest"></param> 84 /// <returns></returns> 85 private string HttpReq(HttpWebRequest myRequest) 86 { 87 //获取接口返回值 88 //通过Web访问对象获取响应内容 89 using (HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse()) 90 { 91 //通过响应内容流创建StreamReader对象,因为StreamReader更高级更快 92 using (StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8)) 93 { 94 //return HttpUtility.UrlDecode(reader.ReadToEnd());//如果有编码问题就用这个方法 95 return reader.ReadToEnd(); 96 } 97 } 98 } 99 100 /// <summary> 101 /// 带有Auth的异步请求 102 /// </summary> 103 /// <param name="uri"></param> 104 /// <param name="methodType"></param> 105 /// <param name="data"></param> 106 /// <param name="auth"></param> 107 /// <param name="ContentType"></param> 108 /// <param name="encoding"></param> 109 /// <returns></returns> 110 private async Task<string> HttpReqWithAuthAsync(string uri, string methodType, string data, string auth, string ContentType = APP_JSON, string encoding = UTF_8) 111 { 112 byte[] buf = Encoding.GetEncoding(encoding).GetBytes(data); 113 HttpWebRequest myRequest = GetHttpWebRequest(uri,methodType,buf,auth,ContentType,encoding); 114 //发送请求 115 using (Stream stream = await myRequest.GetRequestStreamAsync()) 116 { 117 await stream.WriteAsync(buf, 0, buf.Length); 118 } 119 return await HttpReqAsync(myRequest); 120 } 121 /// <summary> 122 /// 不带请求头的直接发送请求,异步版本 123 /// </summary> 124 /// <param name="myRequest"></param> 125 /// <returns></returns> 126 private async Task<string> HttpReqAsync(HttpWebRequest myRequest) 127 { 128 //获取接口返回值 129 //通过Web访问对象获取响应内容 130 using (HttpWebResponse myResponse = (HttpWebResponse)await myRequest.GetResponseAsync()) 131 { 132 //通过响应内容流创建StreamReader对象,因为StreamReader更高级更快 133 using (StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8)) 134 { 135 //return HttpUtility.UrlDecode(reader.ReadToEndAsync());//如果有编码问题就用这个方法 136 return await reader.ReadToEndAsync(); 137 } 138 } 139 } 140 141 /// <summary> 142 /// 得到一个HttpWebRequest对象 143 /// </summary> 144 /// <param name="uri"></param> 145 /// <param name="methodType"></param> 146 /// <param name="buf"></param> 147 /// <param name="auth"></param> 148 /// <param name="ContentType"></param> 149 /// <param name="encoding"></param> 150 /// <returns></returns> 151 private HttpWebRequest GetHttpWebRequest(string uri, string methodType, byte[] buf, string auth, string ContentType = APP_JSON, string encoding = UTF_8) 152 { 153 //创建Web访问对象 154 HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(uri); 155 myRequest.Timeout = TimeOut; 156 myRequest.AllowAutoRedirect = true; 157 158 //把用户传过来的数据转成“UTF-8”的字节流 159 if (!string.IsNullOrEmpty(auth)) 160 { 161 myRequest.Headers.Add(AUTH, auth); 162 //Credentials 163 myRequest.Credentials = CredentialCache.DefaultCredentials; 164 } 165 if (methodType.Equals(GET,StringComparison.OrdinalIgnoreCase)) 166 { 167 return myRequest; 168 } 169 myRequest.Method = methodType; 170 myRequest.ContentLength = buf.Length; 171 myRequest.ContentType = ContentType; 172 myRequest.MaximumAutomaticRedirections = 1; 173 return myRequest; 174 } 175 #endregion 176 177 }
其实我写的时候一直再犹豫同步方法的底层要不要直接重用异步的方法,但是想了下还是分开吧。毕竟底层HttpWebResponse这里是有区分同步异步的。
如果都统一的话意义不大,同步里面塞一堆异步的也不大好,如果你觉得有意义,可以改过去重用。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析