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个错误码,并提供了原因分析和解决方法,有遇到类似问题的 ...
随机推荐
- 【C++】C++中const与constexpr的比较
先说结论相同点:const和consexpr都是用来定义常量的.不同点:const声明的常量,初始值引用的对象不一定是一个常量:constexpr声明的常量,初始值一定是常量表达式. constexp ...
- [U3D Demo] 手机FPS射击游戏
游戏截图 使用插件 DOTween Easy Touch UGUI 游戏介绍 游戏使用C#开发,是在<Unity3D手机游戏开发>一书第3章游戏的基础上优化和修改的. 机枪镭射光线和枪口特 ...
- Openfire 单人聊天和多人聊天(发送消息、接收消息)
Openfire 单人聊天和多人聊天(发送消息.接收消息) 一.单人聊天 1)发送消息: 首先要获取一个聊天窗口,getConnection()为获取连接connection的方法,调用getFrie ...
- oracle去掉字符串中所有指定字符
Select Replace(字段名,'指定字符','替换字符') From 表名 --例: select replace('de.5d','.','') from dual --显示结果:de5d ...
- [python] ThreadPoolExecutor线程池 python 线程池
初识 Python中已经有了threading模块,为什么还需要线程池呢,线程池又是什么东西呢?在介绍线程同步的信号量机制的时候,举得例子是爬虫的例子,需要控制同时爬取的线程数,例子中创建了20个线程 ...
- URLSearchParams和axios的post请求(防忘记)
import axios from 'axios' Vue.prototype.axios = axios mounted () { let params = new URLSearchParams( ...
- Python2.x与3.x版本区别
Python2.x与3.x版本区别 1.print 函数 print语句没有了,取而代之的是print()函数. Python 2.6与Python 2.7部分地支持这种形式的print语法.在Pyt ...
- 微信jssdk常见错误及解决方法
调用config 接口的时候传入参数 debug: true 可以开启debug模式,页面会alert出错误信息.以下为常见错误及解决方法: invalid url domain当前页面所在域名与使用 ...
- git常见用法介绍
1. git help:帮助 git help xxx git xxx --help 2. git init:初始化 git init 3. git config:配置 常见用法 git config ...
- 搞明白GOROOT,GOPATH,GOBIN,project目录
我们接下来一个一个来看关于Go语言中的三个目录的详细解释先通过go env查看go的环境变量(我这里是mac的环境,所以可能和你的不同) localhost:~ zhaofan$ go env GOA ...