• 制作一个简易的RestClient类


    public class RestClient
        {
            private HttpWebRequest CreateHttpRequest(string url, string method)
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                this.SetProxy(request);
                request.Headers.Set("Cache-Control", "No-Cache");
                request.Method = method;
                request.ContentType = "application/json";
                return request;
            }
    
            public virtual T Post<T>(string url, object requestContact) where T : class
            {
                T local;
                HttpWebRequest request = this.CreateHttpRequest(url, "Post");
                if (requestContact != null)
                {
                    using (Stream stream = request.GetRequestStream())
                    {
                        new DataContractJsonSerializer(requestContact.GetType()).WriteObject(stream, requestContact);
                    }
                }
                using (WebResponse response = request.GetResponse())
                {
                    using (Stream stream2 = response.GetResponseStream())
                    {
                        local = new DataContractJsonSerializer(typeof(T)).ReadObject(stream2) as T;
                    }
                }
                return local;
            }
    
            public T Get<T>(string url, object requestContact) where T : class
            {
                T local;
                HttpWebRequest request = this.CreateHttpRequest(url, "GET");
                if (requestContact != null)
                {
                    using (Stream stream = request.GetRequestStream())
                    {
                        new DataContractJsonSerializer(requestContact.GetType()).WriteObject(stream, requestContact);
                    }
                }
                using (WebResponse response = request.GetResponse())
                {
                    using (Stream stream2 = response.GetResponseStream())
                    {
                        local = new DataContractJsonSerializer(typeof(T)).ReadObject(stream2) as T;
                    }
                }
                return local;
            }
    
            private void SetProxy(HttpWebRequest request)
            {
                WebProxy proxy2 = new WebProxy
                {
                    Credentials = CredentialCache.DefaultCredentials
                };
                WebProxy proxy = proxy2;
                request.Proxy = proxy;
            }
        }
    
    一花一世界 一叶一菩提
  • 相关阅读:
    document基本操作 动态脚本-动态样式-创建表格
    js原型模式和继承
    NuGet本地包自定义路径
    技术文档链接收藏
    数据结构排序
    Insertion Sort
    选择排序之javascript
    冒泡排序之javascript
    C++双向链表
    单向链表
  • 原文地址:https://www.cnblogs.com/darjuan/p/2299604.html
Copyright © 2020-2023  润新知