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[];
rng.GetBytes(random);
string NONCE = Math.Abs(BitConverter.ToInt64(random, )).ToString();
//生成时间戳
string TIMESTAMP = ((long)(DateTime.UtcNow - new DateTime(, , , , , , 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";
}
}

最新文章

  1. vertical-align和line-height的那些事
  2. parseInt 和parseFloat 区别
  3. SET ANSI_NULLS ON
  4. 前端--关于HTML
  5. 【C语言探索之旅】 第二部分第四课:字符串
  6. utf8 文件 错误保存为gbk 中文乱码 解决方法
  7. python采用 多进程/多线程/协程 写爬虫以及性能对比,牛逼的分分钟就将一个网站爬下来!
  8. 白话kubernetes的十万个为什么(持续更新中...) - kubernetes
  9. Springboot搭建SSM+JSP的web项目
  10. selenium+Headless Chrome实现不弹出浏览器自动化登录
  11. Problem 1: Multiples of 3 and 5
  12. canvas-9NonZeroAroundPrinciples.html
  13. 【问题解决方案】之 关于某江加密视频swf专用播放器仍无法播放的问题
  14. 开机自动启动WEB服务,共享目录。
  15. Python IDE:pycharm
  16. Linux:挂载、卸载光盘
  17. 过滤器 拦截器 登录login实例
  18. COUNT DISTINCT ROW_NUMBER DENSE_RANK 以及对COUNT去重(非PARTITION)
  19. Jquery 延迟加载框架
  20. VUE脚手架,babel转码 常用命令

热门文章

  1. ROC曲线-阈值评价标准
  2. Scala 隐式(implicit)详解
  3. coon&#39;s patch
  4. 突破这个四个阶段年薪没有50W,还好意思说是搞Java的?
  5. 如何配置JVM系统属性及获取方式System.getProperty(&quot;pname&quot;)
  6. 循环神经网络(Recurrent Neural Networks, RNN)介绍
  7. 软件工程---gjb438b 质量规范体系
  8. 用命令创建MySQL数据库
  9. SSH配置struts校验发生No result defined for action actions.AdminLoginAction and result input
  10. mac xmind 激活