主页 > 知识库 > 网络编程 > ASP/.NET >

一个封装好的Asp.Net C# HttpRequest请求类,可以直接拿来用

来源:博客园 作者:李鹏飞 发表于:2012-08-03 08:36  点击:
一直对于Http的请求都不是很理解,这两天研究了一下,终于搞懂了,就想着拿出来给大家分享一下,希望能够帮到大家。如有不完善的地方,还请多指教。 类我已经写好了,用的是一个C# 的控制台应用程序,包括了调用。 代码如下: HTTP请求类: 双击代码全选 1 2
一直对于Http的请求都不是很理解,这两天研究了一下,终于搞懂了,就想着拿出来给大家分享一下,希望能够帮到大家。如有不完善的地方,还请多指教。
类我已经写好了,用的是一个C# 的控制台应用程序,包括了调用。
代码如下:

HTTP请求类:
双击代码全选
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
View Code 
    
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
    
namespace WebRequestAPP
{
    /// <summary>
    /// Http请求
    /// </summary>
    public class HttpUtility
    {
        /// <summary>
        ///通用HttpWebRequest
        /// </summary>
        /// <param name="method">请求方式(POST/GET)</param>
        /// <param name="url">请求地址</param>
        /// <param name="param">请求参数</param>
        /// <param name="onComplete">完成后执行的操作(可选参数,通过此方法可以获取到HTTP状态码)</param>
        /// <returns>请求返回的结果</returns>
        public static string Request(string method, string url, string param, Action<HttpStatusCode,string> onComplete = null)
        {
            if(string.IsNullOrEmpty(url))
             throw new ArgumentNullException("URL");
    
            switch (method.ToUpper())
            
                case "POST":
                    return Post(url, param, onComplete);
                case "GET":
                    return Get(url, param, onComplete);
                default:
                    throw new EntryPointNotFoundException("method:" + method);
            }
        }
    
        /// <summary>
        /// Post请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="param">参数</param>
        /// <param name="onComplete">完成后执行的操作(可选参数,通过此方法可以获取到HTTP状态码)</param>
        /// <returns>请求返回的结果</returns>
        public static string Post(string url, string param, Action<HttpStatusCode, string> onComplete = null)
        {
            UrlCheck(ref url);
    
            byte[] bufferBytes = Encoding.UTF8.GetBytes(param);
    
            var request = WebRequest.Create(url) as HttpWebRequest;//HttpWebRequest方法继承自WebRequest, Create方法在WebRequest中定义,因此此处要显示的转换
            request.Method = "POST";
            request.ContentLength = bufferBytes.Length;
            request.ContentType = "application/x-www-form-urlencoded";
    
            try
            {
                using (var requestStream = request.GetRequestStream())
                {
                    requestStream.Write(bufferBytes, 0, bufferBytes.Length);
                }
            }
            catch (WebException ex)
            {
    
                return ex.Message;
            }
    
            return HttpRequest(request, onComplete);
        }
    
        /// <summary>
        /// GET请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="param">参数</param>
        /// <param name="onComplete">完成后执行的操作(可选参数,通过此方法可以获取到HTTP状态码)</param>
        /// <returns>请求返回结果</returns>
        public static string Get(string url, string param, Action<HttpStatusCode, string> onComplete = null)
        {
            UrlCheck(ref url);
    
            if (!string.IsNullOrEmpty(param))
                if (!param.StartsWith("?"))
                    param += "?" + param;
                else
                    param += param;
    
            var request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "GET";
            request.ContentType = "application/x-www-form-urlencoded";
    
            return HttpRequest(request, onComplete);
        }
    
        /// <summary>
        /// 请求的主体部分(由此完成请求并返回请求结果)
        /// </summary>
        /// <param name="request">请求的对象</param>
        /// <param name="onComplete">完成后执行的操作(可选参数,通过此方法可以获取到HTTP状态码)</param>
        /// <returns>请求返回结果</returns>
        private static string HttpRequest(HttpWebRequest request, Action<HttpStatusCode, string> onComplete = null)
        {
            HttpWebResponse response = null;
    
            try
            {
                response = request.GetResponse() as HttpWebResponse;
            }
            catch (WebException ex)
            {
                response = ex.Response as HttpWebResponse;
            }
    
            if (response == null)
            {
                if (onComplete != null)
                    onComplete(HttpStatusCode.NotFound, "请求远程返回为空");
                return null;
            }
    
            string result = string.Empty;
            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                result = reader.ReadToEnd();
            }
    
            if (onComplete != null)
                onComplete(response.StatusCode, result);
    
            return result;
    
        }
    
        /// <summary>
        /// URL拼写完整性检查
        /// </summary>
        /// <param name="url">待检查的URL</param>
        private static void UrlCheck(ref string url)
        {
            if (!url.StartsWith("http://") && !url.StartsWith("https://"))
                url="http://"+url;
        }
    }
}
 
调用示例:

有帮助
(0)
0%
没帮助
(5)
100%