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. 画图必备numpy函数

    给定一堆数字,需要统计这些数字中每个数字的个数. 如果这些数字是整数,那自然可以精确统计出来. 如果这些数字是浮点数,如果精确统计会发现几乎每个数字都只出现了一次.所以浮点数就要通过区间的方式进行统计 ...

  2. Oracle&SQLServer中实现跨库查询

    一.在SQLServer中连接另一个SQLServer库数据 在SQL中,要想在本地库中查询另一个数据库中的数据表时,可以创建一个链接服务器: EXEC master.dbo.sp_addlinked ...

  3. mac关闭占用某个端口的进程

    在启动项目的时候有时候会提示端口被占用,但是怎么都找不到那个关闭进程的地方,可以直接通过命令行关闭这个进程: 比如要关闭:8000端口的进程: 1. 查找端口进程: lsof -i: 会把所有的占用8 ...

  4. curl模拟访问已经存在的cookie

    curl 'http://i.meituan.com/brunch/order?status=2' -H 'Pragma: no-cache' -H 'Accept-Encoding: gzip, d ...

  5. Nginx SSL 结合Tomcat 重定向URL变成HTTP的问题

    http://www.siven.net/posts/d925bb5d.html *********************************************** 问题描述 由于要配置服 ...

  6. python faker 生成随机类型字符串

    以前生成测试字符时,用random模块拼来拼去来生成随机串,如姓名,手机,身份证等,还是费一些功夫,不过有了faker模块,一切变得简单起来 基本使用: from faker import Faker ...

  7. Sword 内核队列一

    1.gfifo概述 gfifo是一个First In First Out数据结构,它采用环形循环队列的数据结构来实现:它提供一个无边界的字节流服务,最重要的一点是,它使用并行无锁编程技术,即当它用于只 ...

  8. PXE:另类方式启动 centos live

    default menu.c32 timeout 1 label centos76-live-by-other menu label centos76-live from ftp by other k ...

  9. Web容器初始化过程

    一.SpringMVC启动过程 Spring的MVC是基于Servlet功能实现的,每个web工程中都有一个web.xml文件,web容器在启动的时候会加载这个配置文件,当一个web应用加载到web容 ...

  10. iOS - UITableView中有两种重用Cell的方法

    UITableView中有两种重用Cell的方法: - (id)dequeueReusableCellWithIdentifier:(NSString *)identifier; - (id)dequ ...