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";
}
}

Restsharp常见格式的发送分析的更多相关文章

  1. ffmpeg转换参数和对几种视频格式的转换分析

    我们在将多种格式的视频转换成flv格式的时候,我们关注的就是转换后的flv视频的品质和大小.下面就自己的实践所得来和大家分享一下,主要针对avi.3gp.mp4和wmv四种格式来进行分析.通常在使用f ...

  2. Guid和Int还有Double、Date的ToString方法的常见格式(转载)

    Guid的常见格式: 1.Guid.NewGuid().ToString("N") 结果为:       38bddf48f43c48588e0d78761eaa1ce6 2.Gu ...

  3. Guid和Int还有Double、Date的ToString方法的常见格式

    Guid的常见格式: 1.Guid.NewGuid().ToString("N") 结果为:       38bddf48f43c48588e0d78761eaa1ce6 2.Gu ...

  4. python datetime模块strptime/strptime format常见格式命令_施罗德_新浪博客

    python datetime模块strptime/strptime format常见格式命令_施罗德_新浪博客     python datetime模块strptime/strptime form ...

  5. Mysql Binlog三种格式介绍及分析【转】

    一.Mysql Binlog格式介绍       Mysql binlog日志有三种格式,分别为Statement,MiXED,以及ROW! 1.Statement:每一条会修改数据的sql都会记录在 ...

  6. FFmpeg基础库编程开发学习笔记——视频常见格式

    声明一下:这些关于ffmpeg的文章仅仅是用于记录我的学习历程和以便于以后查阅,文章中的一些文字可能是直接摘自于其它文章.书籍或者文献,学习ffmpeg相关知识是为了使用在Android上,我也才是刚 ...

  7. 常见排序算法总结分析之选择排序与归并排序-C#实现

    本篇文章对选择排序中的简单选择排序与堆排序,以及常用的归并排序做一个总结分析. 常见排序算法总结分析之交换排序与插入排序-C#实现是排序算法总结系列的首篇文章,包含了一些概念的介绍以及交换排序(冒泡与 ...

  8. 【性能测试】常见的性能问题分析思路(二)案例&技巧

    上一篇介绍了性能问题分析的诊断的基本过程,还没看过的可以先看下[性能测试]常见的性能问题分析思路-道与术,精炼总结下来就是,当遇到性能问题的时候,首先分析现场,然后根据现象去查找对应的可能原因,在通过 ...

  9. 【FAQ】接入HMS Core推送服务,服务端下发消息常见错误码原因分析及解决方法

    HMS Core推送服务支持开发者使用HTTPS协议接入Push服务端,可以从服务器发送下行消息给终端设备.这篇文章汇总了服务端下发消息最常见的6个错误码,并提供了原因分析和解决方法,有遇到类似问题的 ...

随机推荐

  1. 【C++】C++中const与constexpr的比较

    先说结论相同点:const和consexpr都是用来定义常量的.不同点:const声明的常量,初始值引用的对象不一定是一个常量:constexpr声明的常量,初始值一定是常量表达式. constexp ...

  2. Select逻辑顺序图

    Select逻辑顺序图

  3. 恶心github 下载慢

    起因 某天看github上面的代码,有点不耐烦,想下载下来再看,但是现在速度慢的可怜 解决思路 相关网站 获取域名相关ip ipaddress.com 这个有好处就是知道网站部署在哪里,如果有vpn的 ...

  4. 文档大师 在Win10 IE11下,文档集画面无法正常显示Word等Office文档的解决方法

    在文档集界面中显示Word文档,是文档大师的一个核心功能. 最近在 Win10 升级到最新版后,发现 无法正常显示Office 文档的问题. 一开始以为是Word版本问题,从2007升级到2016,问 ...

  5. lua中table的遍历,以及删除

    Lua 内table遍历 在lua中有4种方式遍历一个table,当然,从本质上来说其实都一样,只是形式不同,这四种方式分别是: 1. ipairs for index, value in ipair ...

  6. AOSP中的HLS协议解析

    [时间:2018-04] [状态:Open] [关键词:流媒体,stream,HLS, AOSP, 源码分析,HttpLiveSource, LiveSession,PlaylistFetcher] ...

  7. 【python】——python3 与 python2 的那些不兼容

    python2 python3 string.uppercase string.ascii_uppercase string.lowercase string.ascii_lowercase xran ...

  8. spring boot 配置注入

    spring boot配置注入有变量方式和类方式(参见:<spring boot 自定义配置属性的各种方式>),变量中又要注意静态变量的注入(参见:spring boot 给静态变量注入值 ...

  9. 【转】导致SQL执行慢的原因

    索引对大数据的查询速度的提升是非常大的,Explain可以帮你分析SQL语句是否用到相关索引. 索引类似大学图书馆建书目索引,可以提高数据检索的效率,降低数据库的IO成本.MySQL在300万条记录左 ...

  10. Java Spring MVC 错误 及 常见问题 总结

    [参考]spring入门常见的问题及解决办法 错误: 从Git新获取项目 运行出现 1.org.springframework.beans.factory.BeanDefinitionStoreExc ...