C#中的Http访问总结

Posted lionwang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#中的Http访问总结相关的知识,希望对你有一定的参考价值。

第一种是最基本的Http访问,这是同步调用,会有延迟和卡顿:

        /// <summary>
        /// 向服务器发送Request
        /// </summary>
        /// <param name="url">字符串</param>
        /// <param name="method">枚举类型的方法Get或者Post</param>
        /// <param name="body">Post时必须传值</param>
        /// <param name="timeoutSeconds">超时时间,单位秒</param>
        /// <returns></returns>
        public static string Request(string url, MethodEnum method, string body = "", int timeoutSeconds = 15000)
        {
            if (!IsConnectedInternet())
                return "网络连接错误,请稍后再试。";

            try
            {
                GC.Collect();
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Timeout = timeoutSeconds;
                request.Method = method.ToString();
                //如果是Post的话,则设置body
                if (method == MethodEnum.POST)
                {
                    request.ContentType = "application/json";
                    request.KeepAlive = false;
                    byte[] requestBody = Encoding.UTF8.GetBytes(body);
                    request.ContentLength = requestBody.Length;

                    Stream requestStream = request.GetRequestStream();
                    requestStream.Write(requestBody, 0, requestBody.Length);
                }

                return Response(request);
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                    return ex.InnerException.Message;
                if (ex.Message.Contains("已取消一个任务"))
                    return "连接服务器超时,请重试";
                if (ex.Message.Contains("404"))
                    return "连接服务器404,请重试";
                return ex.Message;
            }
        }

        /// <summary>
        /// 返回Response数据
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        private static string Response(HttpWebRequest request)
        {
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            string jsonRead = "";

            if (response.StatusCode != HttpStatusCode.OK)
            {
                return response.StatusCode.ToString();
            }
            //接收过程
            if (response.GetResponseStream() != null)
            {
                StreamReader myStreamReader = new StreamReader(response.GetResponseStream() ?? Stream.Null, Encoding.UTF8);
                jsonRead = myStreamReader.ReadToEnd();
                myStreamReader.Close();
            }
            response.Close();
            request.Abort();

            return jsonRead;
        }

第二种是使用HttpClient来实现异步访问:

  1         public static async void AsyncPost(string url, string body, Action<RequestResult> callback, int timeoutSeconds = 10)
  2         {
  3             var requestResult = new RequestResult();
  4             if (!IsConnectedInternet())
  5             {
  6                 requestResult.Message = "网络连接错误,请稍后再试。";
  7                 callback?.Invoke(requestResult);
  8                 return;
  9             }
 10 
 11             try
 12             {
 13                 using (var client = new HttpClient())
 14                 {
 15                     client.Timeout = new TimeSpan(0, 0, timeoutSeconds);
 16                     //byte[] requestBody = Encoding.UTF8.GetBytes(body);
 17                     HttpContent content = new StringContent(body);
 18                     content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
 19                     var response = await client.PostAsync(url, content);
 20                     //确保HTTP成功状态值
 21                     response.EnsureSuccessStatusCode();
 22                     //await异步读取最后的JSON
 23                     await response.Content.ReadAsStringAsync().ContinueWith(t =>
 24                     {
 25                         if (t.IsCompleted)
 26                         {
 27                             requestResult.IsSuccess = true;
 28                             requestResult.Result = t.Result;
 29                             callback?.Invoke(requestResult);
 30                         }
 31                     });
 32                 }
 33             }
 34             catch (Exception e)
 35             {
 36                 if (e.InnerException != null)
 37                     requestResult.Message = e.InnerException.Message;
 38                 else if (e.Message.Contains("已取消一个任务"))
 39                     requestResult.Message = "连接服务器超时,请重试";
 40                 else if (e.Message.Contains("404"))
 41                     requestResult.Message = "连接服务器404,请重试";
 42                 else
 43                     requestResult.Message = e.Message;
 44                 callback?.Invoke(requestResult);
 45             }
 46         }
 47 
 48         public static async void AsyncGet(string url, Action<RequestResult> callback, int timeoutSeconds = 10)
 49         {
 50             var requestResult = new RequestResult();
 51             if (!IsConnectedInternet())
 52             {
 53                 requestResult.Message = "网络连接错误,请稍后再试。";
 54                 callback?.Invoke(requestResult);
 55                 return;
 56             }
 57 
 58             try
 59             {
 60                 using (var client = new HttpClient())
 61                 {
 62                     client.Timeout = new TimeSpan(0, 0, timeoutSeconds);
 63                     var response = await client.GetAsync(url);
 64                     //确保HTTP成功状态值
 65                     response.EnsureSuccessStatusCode();
 66                     //await异步读取最后的JSON
 67                     await response.Content.ReadAsStringAsync().ContinueWith(t =>
 68                     {
 69                         if (t.IsCompleted)
 70                         {
 71                             requestResult.IsSuccess = true;
 72                             requestResult.Result = t.Result;
 73                             callback?.Invoke(requestResult);
 74                         }
 75                     });
 76                 }
 77             }
 78             catch (Exception e)
 79             {
 80                 if (e.InnerException != null)
 81                     requestResult.Message = e.InnerException.Message;
 82                 else if (e.Message.Contains("已取消一个任务"))
 83                     requestResult.Message = "连接服务器超时,请重试";
 84                 else if (e.Message.Contains("404"))
 85                     requestResult.Message = "连接服务器404,请重试";
 86                 else
 87                     requestResult.Message = e.Message;
 88                 callback?.Invoke(requestResult);
 89             }
 90         }
 91 
 92         public static async void AsyncPut(string url, string body, Action<RequestResult> callback, int timeoutSeconds = 10)
 93         {
 94             var requestResult = new RequestResult();
 95             if (!IsConnectedInternet())
 96             {
 97                 requestResult.Message = "网络连接错误,请稍后再试。";
 98                 callback?.Invoke(requestResult);
 99                 return;
100             }
101 
102             try
103             {
104                 using (var client = new HttpClient())
105                 {
106                     client.Timeout = new TimeSpan(0, 0, timeoutSeconds);
107                     HttpContent content = new StringContent(body);
108                     content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
109                     var response = await client.PutAsync(url, content);
110                     //确保HTTP成功状态值
111                     response.EnsureSuccessStatusCode();
112                     //await异步读取最后的JSON
113                     await response.Content.ReadAsStringAsync().ContinueWith(t =>
114                     {
115                         if (t.IsCompleted)
116                         {
117                             requestResult.IsSuccess = true;
118                             requestResult.Result = t.Result;
119                             callback?.Invoke(requestResult);
120                         }
121                     });
122                 }
123             }
124             catch (Exception e)
125             {
126                 if (e.InnerException != null)
127                     requestResult.Message = e.InnerException.Message;
128                 else if (e.Message.Contains("已取消一个任务"))
129                     requestResult.Message = "连接服务器超时,请重试";
130                 else if (e.Message.Contains("404"))
131                     requestResult.Message = "连接服务器404,请重试";
132                 else
133                     requestResult.Message = e.Message;
134                 callback?.Invoke(requestResult);
135             }
136         }
137 
138         public static async void AsyncDelete(string url, Action<RequestResult> callback, int timeoutSeconds = 10)
139         {
140             var requestResult = new RequestResult();
141             if (!IsConnectedInternet())
142             {
143                 requestResult.Message = "网络连接错误,请稍后再试。";
144                 callback?.Invoke(requestResult);
145                 return;
146             }
147 
148             try
149             {
150                 using (var client = new HttpClient())
151                 {
152                     client.Timeout = new TimeSpan(0, 0, timeoutSeconds);
153                     var response = await client.DeleteAsync(url);
154                     //确保HTTP成功状态值
155                     response.EnsureSuccessStatusCode();
156                     //await异步读取最后的JSON
157                     await response.Content.ReadAsStringAsync().ContinueWith(t =>
158                     {
159                         if (t.IsCompleted)
160                         {
161                             requestResult.IsSuccess = true;
162                             requestResult.Result = t.Result;
163                             callback?.Invoke(requestResult);
164                         }
165                     });
166                 }
167             }
168             catch (Exception e)
169             {
170                 if (e.InnerException != null)
171                     requestResult.Message = e.InnerException.Message;
172                 else if (e.Message.Contains("已取消一个任务"))
173                     requestResult.Message = "连接服务器超时,请重试";
174                 else if (e.Message.Contains("404"))
175                     requestResult.Message = "连接服务器404,请重试";
176                 else
177                     requestResult.Message = e.Message;
178                 callback?.Invoke(requestResult);
179             }
180         }

定义一个异步返回信息的类:

 1     public class RequestResult : IDisposable
 2     {
 3         public bool IsSuccess { get; set; }
 4 
 5         public string Result { get; set; }
 6 
 7         public string Message { get; set; }
 8 
 9         public RequestResult(bool isSuccess = false, string result = "", string message = "")
10         {
11             IsSuccess = isSuccess;
12             Result = result;
13             Message = message;
14         }
15         
16         ~RequestResult()
17         {
18             Dispose();
19         }
20 
21         public void Dispose()
22         {
23             Dispose(true);
24             GC.SuppressFinalize(this);//不需要再调用本对象的Finalize方法
25         }
26 
27         protected virtual void Dispose(Boolean disposing)
28         {
29             if (disposing)
30             {
31                 //--- 清理托管资源 ---//
32             }
33 
34             //--- 清理非托管资源 ---//
35         }
36     }

附带一个检测网络连接状态的方法:

 1         [DllImport("winInet.dll")]
 2         private static extern bool InternetGetConnectedState(ref int dwFlag, int dwReserved);
 3 
 4         /// <summary>
 5         /// 用于检查网络是否可以连接互联网,true表示连接成功,false表示连接失败 
 6         /// </summary>
 7         /// <returns></returns>
 8         private static bool IsConnectedInternet()
 9         {
10             int description = 0;
11             return InternetGetConnectedState(ref description, 0);
12         }

 

以上是关于C#中的Http访问总结的主要内容,如果未能解决你的问题,请参考以下文章

比较 C# 中的字符串片段并从集合中删除项目

c# https请求忽略证书验证_各种编程语言忽略http的SSL证书认证

XSS:如何从 C# 中的字符串中删除 JS 片段?

C#复习总结匿名类型由来

回归 | js实用代码片段的封装与总结(持续更新中...)

C# 最有用的(自定义)代码片段是啥? [关闭]