Restsharp常见格式的发送分析

1.传递匿名对象JSON格式

 public string Pay(string apisecret, string apikey, string token)
        {
            try
            {
                string url = "https://******//test";            
                var client = new RestClient(url);             
          var request = new RestRequest(Method.POST);
                var tran = new
                {
                    merchant_ref = "Astonishing-Sale",
                    transaction_type = "purchase"
                };
                //生成随机数
                RandomNumberGenerator rng = RNGCryptoServiceProvider.Create();
                byte[] random = new Byte[8];
                rng.GetBytes(random);
                string NONCE = Math.Abs(BitConverter.ToInt64(random, 0)).ToString();
                //生成时间戳
                string TIMESTAMP = ((long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds).ToString();
                //获取JSON字符内容
                string paybody = string.Empty;

                if (tran.transaction_type != null)
                {
                    paybody = SimpleJson.SerializeObject(tran);
                }
  
                string auth = GetAuth(apisecret, apikey, token, paybody, NONCE, TIMESTAMP);
                request.AddHeader("Content-Type", "application/json");
                request.AddHeader("apikey", apikey);
                request.AddHeader("token", token);
                request.AddHeader("Authorization", auth);
                request.AddHeader("nonce", NONCE);
                request.AddHeader("timestamp", TIMESTAMP);
                request.AddJsonBody(tran);//自动转换为JSON
                IRestResponse response = client.Execute(request);
                var content = response.Content;               return content;
            }
            catch (Exception e)
            {return string.Empty;

            }
        }

 

  

 

2.multipart/form-data上传文件

根据Restsharp源码可以发现如果使用了AddFile了会自动添加multipart/form-data参数           

            string server = "http://*****//Upload";
            string picurl = "C:\\Users\\Administrator\\Desktop\\555.png";
            string testparams = "testpicupload";
            RestClient restClient = new RestClient(server);
            //restClient.Encoding = Encoding.GetEncoding("GBK");//设置编码格式
            RestRequest restRequest = new RestRequest("/images");
            restRequest.RequestFormat = DataFormat.Json;
            restRequest.Method = Method.POST;
            //restRequest.AddHeader("Authorization", "Authorization");//当需要设置认证Token等情况时使用默认不需要
            //restRequest.AddHeader("Content-Type", "multipart/form-data");//如果使用了AddFile会自动添加否则请手动设置
            restRequest.AddParameter("test", testparams);
            // restRequest.AddFile("pic", picurl);//压缩格式
            restRequest.AddFile("pic", picurl, contentType: "application/x-img");    //非压缩格式 如果此处不设置为contentType 则默认压缩格式
            var response = restClient.Execute(restRequest);
            var info= response.Content;

 

 

3.直接传递不带参数的RequestBody:有的时候接口并不包含参数名而是直接以body流的方式传输的这时候使用上面添加参数的方式就无效了,如果发送呢,RestSharp里保留了AddBody和 ParameterType.RequestBody来实现

request.AddParameter("text/xml", body, ParameterType.RequestBody);
req.AddParameter("application/json", body, ParameterType.RequestBody);

  

根据AddBody源码发现实际转换最终使用的都是 AddParameter(contentType, serialized, ParameterType.RequestBody) 这个方法

 public IRestRequest AddBody(object obj, string xmlNamespace)
        {
            string serialized;
            string contentType;
            switch (this.RequestFormat)
            {
                case DataFormat.Json:
                    serialized = this.JsonSerializer.Serialize(obj);
                    contentType = this.JsonSerializer.ContentType;
                    break;
                case DataFormat.Xml:
                    this.XmlSerializer.Namespace = xmlNamespace;
                    serialized = this.XmlSerializer.Serialize(obj);
                    contentType = this.XmlSerializer.ContentType;
                    break;
                default:
                    serialized = "";
                    contentType = "";
                    break;
            }

            // passing the content type as the parameter name because there can only be
            // one parameter with ParameterType.RequestBody so name isn't used otherwise
            // it's a hack, but it works :)
            return this.AddParameter(contentType, serialized, ParameterType.RequestBody);
        }
 /// <summary>
        /// Adds a parameter to the request. There are four types of parameters:
        /// - GetOrPost: Either a QueryString value or encoded form value based on method
        /// - HttpHeader: Adds the name/value pair to the HTTP request's Headers collection
        /// - UrlSegment: Inserted into URL if there is a matching url token e.g. {AccountId}
        /// - RequestBody: Used by AddBody() (not recommended to use directly)
        /// </summary>
        /// <param name="name">Name of the parameter</param>
        /// <param name="value">Value of the parameter</param>
        /// <param name="type">The type of parameter to add</param>
        /// <returns>This request</returns>
        public IRestRequest AddParameter(string name, object value, ParameterType type)
        {
            return this.AddParameter(new Parameter
                                     {
                                         Name = name,
                                         Value = value,
                                         Type = type
                                     });
        }
  
       

4..二进制数据:(如下方式发送的格式和直接使用二进制写入是相同的)

            string server = "http://******/Upload";
            RestClient restClient = new RestClient(server);
            restClient.Encoding = Encoding.GetEncoding("GBK");//设置编码格式
            RestRequest restRequest = new RestRequest(Method.POST);          
            restRequest.Method = Method.POST;   
            var bb = new byte[] { 0x30, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x12, 0x40, 0x42 };     
            restRequest.AddParameter("application/pdf", bb, ParameterType.RequestBody);
            var response = restClient.Execute(restRequest);
            string s = response.Content;

 测试Demo:

  [TestMethod]
        public void TestRestsharpBinaryBody()
        {
             string server = "http://******/Upload";
            RestClient restClient = new RestClient(server);
            restClient.Encoding = Encoding.GetEncoding("GBK");//设置编码格式
            RestRequest request = new RestRequest(Method.POST);
            request.Method = Method.POST;

            //===========二进制===测试通过=================
            //var bb = new byte[] { 0x30, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38,0x40, 0x42 };            
            //request.AddParameter("application/pdf", bb, ParameterType.RequestBody);

            //==============XML字符串=====测试通过==============    
            /**
             * 发送内容
             * <root></root>
             * */
            string x = "<root></root>";//XML字符串
            request.AddParameter("text/xml", x, ParameterType.RequestBody);

            //=============Json转换==================
            /**
             * 发送内容
             * {"id":1,"name":"zhangsan"}
             * */
            //var x = new { id = 1, name = "zhangsan" };
            //request.AddJsonBody(x);

            //============object转XML==============  
            /**
             * 发送内容
             * <Dummy>
                 <A>Some string</A>
                 <B>Some string</B>
               </Dummy>
             * */
            //request.AddXmlBody(new Dummy());//对象转XML 非匿名对象可以 匿名对象失败

            /***
             * 发送内容
            <Dummy xmlns="Root">
                  <A>Some string</A>
                  <B>Some string</B>
            </Dummy>
             * */
            request.AddXmlBody(new Dummy(),"Root");//对象转XML 非匿名对象可以 匿名对象失败 Root为命名空间           
            var response = restClient.Execute(request);
            string s = response.Content;
            Assert.IsNotNull(response.Content);
        }
public  class Dummy
    {
        public string A { get; set; }
        public string B { get; set; }

        public Dummy()
        {
            A = "Some string";
            B = "Some string";
        }
    }

 

posted @ 2017-06-28 15:00  Merray  Views(5152)  Comments(0Edit  收藏  举报