C#中Get和Post请求的同步及异步方法

在C#中发起Http请求一般使用HttpWebRequest这个类,下文将使用这个HttpWebRequest对象来对Get和Post的同步及异步请求进行封装:

1. 新建HttpRequestHelper类:

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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
public static class  HttpRequestHelper
    {
        /// <summary>
        /// Http Get Request
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string HttpGetRequest(string url)
        {
            string strGetResponse = string.Empty;
            try
            {
                var getRequest = CreateHttpRequest(url, "GET");
                var getResponse = getRequest.GetResponse() as HttpWebResponse;
                strGetResponse = GetHttpResponse(getResponse, "GET");
            }
            catch (Exception ex)
            {
                strGetResponse = ex.Message;
            }
            return strGetResponse;
        }
 
        /// <summary>
        /// Http Get Request Async
        /// </summary>
        /// <param name="url"></param>
        public static async void HttpGetRequestAsync(string url)
        {
            string strGetResponse = string.Empty;
            try
            {
                var getRequest = CreateHttpRequest(url, "GET");
                var getResponse = await getRequest.GetResponseAsync() as HttpWebResponse;
                strGetResponse = GetHttpResponse(getResponse, "GET");
            }
            catch (Exception ex)
            {
                strGetResponse = ex.Message;
            }
            return strGetResponse;
            Console.WriteLine("reslut:" + strGetResponse);
        }
 
        /// <summary>
        /// Http Post Request
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postJsonData"></param>
        /// <returns></returns>
        public static string HttpPostRequest(string url, string postJsonData)
        {
            string strPostReponse = string.Empty;
            try
            {
                var postRequest = CreateHttpRequest(url, "POST", postJsonData);
                var postResponse = postRequest.GetResponse() as HttpWebResponse;
                strPostReponse = GetHttpResponse(postResponse, "POST");
            }
            catch (Exception ex)
            {
                strPostReponse = ex.Message;
            }
            return strPostReponse;
        }
 
        /// <summary>
        /// Http Post Request Async
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postJsonData"></param>
        public static async void HttpPostRequestAsync(string url, string postData)
        {
            string strPostReponse = string.Empty;
            try
            {
                var postRequest = CreateHttpRequest(url, "POST", postData);
                var postResponse = await postRequest.GetResponseAsync() as HttpWebResponse;
                strPostReponse = GetHttpResponse(postResponse, "POST");
            }
            catch (Exception ex)
            {
                strPostReponse = ex.Message;
            }
            if (strPostReponse != "true")
            {
                Console.WriteLine("--> reslut : " + strPostReponse);
                Console.WriteLine(postData);
            }
        }
 
        private static HttpWebRequest CreateHttpRequest(string url, string requestType, params object[] strJson)
        {
            HttpWebRequest request = null;
            const string get = "GET";
            const string post = "POST";
            if (string.Equals(requestType, get, StringComparison.OrdinalIgnoreCase))
            {
                request = CreateGetHttpWebRequest(url);
            }
            if (string.Equals(requestType, post, StringComparison.OrdinalIgnoreCase))
            {
                request = CreatePostHttpWebRequest(url, strJson[0].ToString());
            }
            return request;
        }
 
        private static HttpWebRequest CreateGetHttpWebRequest(string url)
        {
            var getRequest = HttpWebRequest.Create(url) as HttpWebRequest;
            getRequest.Method = "GET";
            getRequest.Timeout = 5000;
            getRequest.ContentType = "text/html;charset=UTF-8";
            getRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            return getRequest;
        }
 
        private static HttpWebRequest CreatePostHttpWebRequest(string url, string postData)
        {
            var postRequest = HttpWebRequest.Create(url) as HttpWebRequest;
            postRequest.KeepAlive = false;
            postRequest.Timeout = 5000;
            postRequest.Method = "POST";
            postRequest.ContentType = "application/x-www-form-urlencoded";
            postRequest.ContentLength = postData.Length;
            postRequest.AllowWriteStreamBuffering = false;
            StreamWriter writer = new StreamWriter(postRequest.GetRequestStream(), Encoding.ASCII);
            writer.Write(postData);
            writer.Flush();
            return postRequest;
        }
 
        private static string GetHttpResponse(HttpWebResponse response, string requestType)
        {
            var responseResult = "";
            const string post = "POST";
            string encoding = "UTF-8";
            if (string.Equals(requestType, post, StringComparison.OrdinalIgnoreCase))
            {
                encoding = response.ContentEncoding;
                if (encoding == null || encoding.Length < 1)
                {
                    encoding = "UTF-8";
                }
            }
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding)))
            {
                responseResult = reader.ReadToEnd();
            }
            return responseResult;
        }
 
        private static string GetHttpResponseAsync(HttpWebResponse response, string requestType)
        {
            var responseResult = "";
            const string post = "POST";
            string encoding = "UTF-8";
            if (string.Equals(requestType, post, StringComparison.OrdinalIgnoreCase))
            {
                encoding = response.ContentEncoding;
                if (encoding == null || encoding.Length < 1)
                {
                    encoding = "UTF-8";
                }
            }
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding)))
            {
                responseResult = reader.ReadToEnd();
            }
            return responseResult;
        }
    }

  

2. 使用

2.1  同步请求

复制代码
// Get
     var getUrl = "http://localhost:8888?";
     HttpRequestHelper.HttpGetRequest(getUrl);

     // Post
     var postUrl = "http://localhost:8888";
     var postObj = new
     {
          username = "DamonZhu",
          password = "12345678"
     };
     var postData = JsonConvert.SerializeObject(postObj);
     HttpRequestHelper.HttpPostRequest(postUrl, postData);
复制代码

2.2 异步请求

复制代码
// Get Async
    var getUrl = "http://localhost:8888?";
    HttpRequestHelper.HttpGetRequestAsync(getUrl);

    // Post Async
    var postUrl = "http://localhost:8888";
    var postObj = new
    {
        username = "DamonZhu",
        password = "12345678"
    };
    var postData = JsonConvert.SerializeObject(postObj);
    HttpRequestHelper.HttpPostRequestAsync(postUrl, postData);
复制代码

 其他:

复制代码
   private async Task<string> ServicePostRequest(string url, string parameters)
        {
            string result = String.Empty;

            using (var client = new HttpClient())
            {
                HttpContent content = new StringContent(parameters);
                content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");
                client.Timeout = new TimeSpan(0, 0, 15);
                using (var response = await client.PostAsync(url, content))
                {
                    using (var responseContent = response.Content)
                    {
                        result = await responseContent.ReadAsStringAsync();
                        Console.WriteLine(result);
                        return result;
                    }
                }
            }
        }
复制代码

 

posted @   流氓大菠萝  阅读(1319)  评论(1编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示