1. 程式人生 > >c#模擬http請求類

c#模擬http請求類

    public class HttpHelper
    {
        public static string Request(string url, Dictionary<string, dynamic> args, Encoding encoding, Dictionary<string, string> headers = null,
            HttpMethod method = HttpMethod.POST, string contentType = "application/json")
        {

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = method.ToString();
                request.Timeout = 100000;
                request.UserAgent =
                    "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36 QIHU 360EE";
                if (headers != null)
                {
                    foreach (var item in headers)
                    {
                        request.Headers.Add(item.Key, item.Value);
                    }
                }
                request.ContentType = contentType;
                byte[] data = new byte[0];
                if (args != null)
                {
                    data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(JsonConvert.SerializeObject(args)));
                }
                request.ContentLength = data.Length;
                if (request.ContentLength>0)
                {
                    using (Stream writer = request.GetRequestStream())
                    {
                        writer.Write(data, 0, data.Length);
                    } 
                } 
                using (StreamReader reader = new StreamReader(request.GetResponse().GetResponseStream(), encoding))
                {
                    return reader.ReadToEnd();
                }
            }
            catch (Exception e)
            {
                return e.Message;
            }
        }

    }

    public enum HttpMethod
    {
        POST,
        GET,
        DELETE,
        PUT
    }