封装简单的HTTP操作类

项目当中时长会遇到进行HTTP请求的时候,遇得多了,自己写了一个简易的辅助类,通过HttpClient进行各种请求操作,毫无技术含量,仅在此分享一下。

 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
    /// <summary>
    /// HTTP操作辅助类
    /// </summary>
    public class HttpMethodUtils
    {
        private readonly HttpClient m_reqClient;
        public HttpMethodUtils() => m_reqClient = new HttpClient();

        /// <summary>
        /// 对目标地址进行Get请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="parameters">原始参数列表</param>
        /// <param name="referer">引用来源</param>
        /// <returns>请求结果</returns>
        public string Get(string url, object parameters = null, string referer = null)
        {
            if (string.IsNullOrEmpty(url)) return null;

            var _req = new HttpRequestMessage()
            {
                Method = HttpMethod.Get,
                RequestUri = new Uri($"{url}{buildHttpGetParameters(parameters)}")
            };

            if (referer != null) _req.Headers.Referrer = new Uri(referer);

            using (HttpResponseMessage _msg = m_reqClient.SendAsync(_req).Result)
            {
                if (_msg.StatusCode != HttpStatusCode.OK) return null;
                return _msg.Content.ReadAsStringAsync().Result;
            }
        }

        /// <summary>
        /// 对目标地址进行POST请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="paramters">提交的参数</param>
        /// <param name="referer">调用来源</param>
        /// <param name="mediaTypeValue">参数类型</param>
        /// <returns>调用结果</returns>
        public string Post(string url, object paramters = null, string referer = null, string mediaTypeValue = null)
        {
            if (string.IsNullOrEmpty(url)) return null;
            var _req = new HttpRequestMessage()
            {
                Method = HttpMethod.Post,
                RequestUri = new Uri(url)
            };

            if (referer != null) _req.Headers.Referrer = new Uri(referer);
            if (paramters != null)
            {
                _req.Content = new StringContent(buildHttpGetParameters(paramters));
                _req.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(mediaTypeValue);
            }

            using (var _msg = m_reqClient.SendAsync(_req).Result)
            {
                if (_msg.StatusCode != HttpStatusCode.OK) return null;
                return _msg.Content.ReadAsStringAsync().Result;
            }
        }

        /// <summary>
        /// 构建HTTP的GET方法的参数
        /// </summary>
        /// <param name="param">传入的参数模型</param>
        /// <returns>成功返回构造成功的参数列表,失败返回String.Empty</returns>
        private string buildHttpGetParameters(object param)
        {
            if (param == null) return string.Empty;

            var _type = param.GetType();
            var _propertys = _type.GetProperties();
            StringBuilder _builder = new StringBuilder();
            _builder.Append('?');

            foreach (var item in _propertys)
            {
                _builder.Append($"{item.Name}={item.GetValue(param)}&");
            }

            return _builder.ToString().TrimEnd('&');
        }
    }

上文当中,唯一有一点技巧的地方,就是通过反射来获得匿名对象的属性进行构造参数,这里仅作拼接,其实可以构造成一个JSON进行POST提交,某些地方需要。 调用示例:

1
2
3
4
5
6
7
8
var _postParam = new 
{
   token = "xxxxxxx",
   page = 10
}

var _net = new HttpMethodUtils();
_net.Get("http://www.baidu.com",_postParam);
Licensed under CC BY-NC-SA 4.0
Built with Hugo
主题 StackJimmy 设计