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[];
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常见格式的发送分析的更多相关文章
- ffmpeg转换参数和对几种视频格式的转换分析
我们在将多种格式的视频转换成flv格式的时候,我们关注的就是转换后的flv视频的品质和大小.下面就自己的实践所得来和大家分享一下,主要针对avi.3gp.mp4和wmv四种格式来进行分析.通常在使用f ...
- Guid和Int还有Double、Date的ToString方法的常见格式(转载)
Guid的常见格式: 1.Guid.NewGuid().ToString("N") 结果为: 38bddf48f43c48588e0d78761eaa1ce6 2.Gu ...
- Guid和Int还有Double、Date的ToString方法的常见格式
Guid的常见格式: 1.Guid.NewGuid().ToString("N") 结果为: 38bddf48f43c48588e0d78761eaa1ce6 2.Gu ...
- python datetime模块strptime/strptime format常见格式命令_施罗德_新浪博客
python datetime模块strptime/strptime format常见格式命令_施罗德_新浪博客 python datetime模块strptime/strptime form ...
- Mysql Binlog三种格式介绍及分析【转】
一.Mysql Binlog格式介绍 Mysql binlog日志有三种格式,分别为Statement,MiXED,以及ROW! 1.Statement:每一条会修改数据的sql都会记录在 ...
- FFmpeg基础库编程开发学习笔记——视频常见格式
声明一下:这些关于ffmpeg的文章仅仅是用于记录我的学习历程和以便于以后查阅,文章中的一些文字可能是直接摘自于其它文章.书籍或者文献,学习ffmpeg相关知识是为了使用在Android上,我也才是刚 ...
- 常见排序算法总结分析之选择排序与归并排序-C#实现
本篇文章对选择排序中的简单选择排序与堆排序,以及常用的归并排序做一个总结分析. 常见排序算法总结分析之交换排序与插入排序-C#实现是排序算法总结系列的首篇文章,包含了一些概念的介绍以及交换排序(冒泡与 ...
- 【性能测试】常见的性能问题分析思路(二)案例&技巧
上一篇介绍了性能问题分析的诊断的基本过程,还没看过的可以先看下[性能测试]常见的性能问题分析思路-道与术,精炼总结下来就是,当遇到性能问题的时候,首先分析现场,然后根据现象去查找对应的可能原因,在通过 ...
- 【FAQ】接入HMS Core推送服务,服务端下发消息常见错误码原因分析及解决方法
HMS Core推送服务支持开发者使用HTTPS协议接入Push服务端,可以从服务器发送下行消息给终端设备.这篇文章汇总了服务端下发消息最常见的6个错误码,并提供了原因分析和解决方法,有遇到类似问题的 ...
随机推荐
- GPL、BSD、MIT、Mozilla、Apache、LGPL开源协议介绍
BSD开源协议 BSD开源协议是一个给于使用者很大自由的协议.基本上使用者可以”为所欲为”,可以自由的使用,修改源代码,也可以将修改后的代码作为开源或者专有软件再发布. 但”为所欲为”的前提当你发布使 ...
- 【C++】C++中的字符和字符串
目录结构: contents structure [-] 定义和初始化string string对象上的操作 处理string对象中的字符 C风格字符串 标准库类型string表示可变长的字符序列,使 ...
- 基础008_定浮点转化[floating point IP]
作者:桂. 时间:2018-05-15 21:55:50 链接:http://www.cnblogs.com/xingshansi/p/9042564.html 前言 本文为Xilinx float ...
- 【转载】MapReduce编程 Intellij Idea配置MapReduce编程环境
目录(?)[-] 一软件环境 二创建maven工程 三添加maven依赖 四配置log4j 五启动Hadoop 六运行WordCount从本地读取文件 七运行WordCount从HDFS读取文件 八代 ...
- Mac安装minikube
安装过程 先安装minikube,使用下面命令(由于墙的问题,所以指定国内的地址) curl -Lo minikube http://kubernetes.oss-cn-hangzhou.aliyun ...
- Content of "Essential Software Test Design"
Content of "Essential Software Test Design" 2015-11-16 PART I 7 TEST DESIGN TECHNIQUES: AN ...
- python多线程应用——DB2数据库备份
前言:DB2一个实例下,可以存在多个数据库,之前使用shell备份脚本,但是同一时刻只能备份一个数据库,对于几百G的备份文件,这个速度显然太慢,今天学习了Python多线程,刚好应用一下. 分析:1. ...
- 牛客网_Go语言相关练习_判断&选择题(6)
本文共34道题目 一.判断题 此题考查编码规范. 反射最常见的使用场景是做对象的序列化(serialization,有时候也叫Marshal & Unmarshal). 例如:Go语言标准库的 ...
- flask多个app应用组合
由于之前写得接口太多了,分为了多个app,每个app里面有几个接口.部署次数需要很多次,修改成部署一次,在不改变代码的情况下,不使用蓝图,最快的方式就是这样修改. from werkzeug.wsgi ...
- python中基本类型的连接组合和互相转换
本篇总结了一下字符串,列表,字典,元组的连接组合使用和类型的互相转换小例子,尤其列表中的extend()方法和字典中的 update方法非常的常用. 1.连接两个字符串 a = "hello ...