tangxu
2024-03-20 d02b0ea2776bbec9c23b56a5b107a027bc7bcb84
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
using System;
using System.IO;
using System.Net;
 
namespace IStation.WinFrmUI.CalcErQu
{
    /// <summary>
    /// HTTP请求辅助类
    /// </summary>
    public class HttpRequestHelper
    {
        /// <summary>
        /// 获取
        /// </summary>
        public static string Get(string url, Version version = null)
        {
            return Request(url, "GET", null, version);
        }
 
        /// <summary>
        /// 提交
        /// </summary>
        public static string Post(string url, string data = null, Version version = null)
        {
            return Request(url, "POST", data, version);
        }
 
 
        //请求
        private static string Request(string url, string type, string data = null, Version version = null)
        {
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = type;
            request.ContentType = "application/json";
            request.KeepAlive = false;
            if (version != null)
            {
                //默认是HttpVersion.Version11
                request.ProtocolVersion = version;
            }
 
            #region 注释
            /*request.Timeout = 10 * 1000;//请求超时时间
            if (!string.IsNullOrEmpty(data))
            {
                request.ContentLength = Encoding.UTF8.GetBytes(data).Length;
            }*/
            #endregion
 
            if (!string.IsNullOrEmpty(data))
            {
                using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                {
                    streamWriter.Write(data);
                    streamWriter.Flush();
                }
            }
 
            string responseText;
            using (var response = (HttpWebResponse)request.GetResponse())
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                responseText = reader.ReadToEnd();
            }
            return responseText;
        }
 
 
 
    }
}