ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

C# 使用RestSharp实现Postman中的各种形式的请求

2022-04-14 14:32:34  阅读:159  来源: 互联网

标签:Postman C# item JSON 添加 cookie Cookie RestSharp string


 

https://blog.csdn.net/qq_31025841/article/details/120448324

一、导入命名空间
二、构建客户端
◆ 创建客户端对象
◆ 设置当前URL
◆ 设置响应超时
◆ 添加默认Header
◆ 添加单项Cookie
◆ 添加多项Cookie
三、构建请求
◆ 创建请求对象
◆ 添加参数Header
◆ 添加单项Cookie
◆ 添加多项Cookie
◆ 添加参数Params
◆ 添加参数Body
> form-data和x-www-form-urlencoded
> JSON数据
> File上传
四、执行Request请求
◆ JSON结果
◆ File下载
★ 小技巧 ★ :
淘宝平台Sign算法
一、导入命名空间
using RestSharp;
using Newtonsoft.Json; // 用于JSON序列化/反序列化
using Newtonsoft.Json.Linq; // 用于构建JSON对象
1
2
3
二、构建客户端
◆ 创建客户端对象
RestClient client = new RestClient();
1
◆ 设置当前URL
client.BaseUrl = new Uri("https://www.baidu.com/s");
1
◆ 设置响应超时
client.Timeout = -1; // 永不超时
1
◆ 添加默认Header
client.AddDefaultHeader("HeaderKey", "HeaderValue");
1
◆ 添加单项Cookie
client.AddDefaultParameter("itemKey", "itemValue", ParameterType.Cookie);
1
◆ 添加多项Cookie
public void addClientCookies(ref RestClient client, string cookie)
{
string[] cookie_items = cookie.Split(';');
foreach (string cookie_item in cookie_items)
{
if (cookie_item.Trim().Length == 0) continue;
string cookie_key = cookie_item.Substring(0, cookie_item.IndexOf('=')).Trim();
string cookie_value = cookie_item.Substring(cookie_item.IndexOf('=') + 1).Trim();
if (cookie_value.Contains(",")) cookie_value = $"\"{cookie_value}\"";
client.AddDefaultParameter(cookie_key, cookie_value, ParameterType.Cookie);
}
}
// 调用示例
addClientCookies(ref client, "item1=value1;item2=value2")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
三、构建请求
◆ 创建请求对象
RestRequest request = new RestRequest(Method.GET); // Post请求:Method.POST
1
◆ 添加参数Header
request.AddHeader("HeaderKey", "HeaderValue");
1
◆ 添加单项Cookie
request.AddParameter("itemName", "itemValue", ParameterType.Cookie);
1
◆ 添加多项Cookie
public void addRequestCookies(ref RestRequest request, string cookie)
{
string[] cookie_items = cookie.Split(';');
foreach (string cookie_item in cookie_items)
{
if (cookie_item.Trim().Length == 0) continue;
string cookie_key = cookie_item.Substring(0, cookie_item.IndexOf('=')).Trim();
string cookie_value = cookie_item.Substring(cookie_item.IndexOf('=') + 1).Trim();
if (cookie_value.Contains(",")) cookie_value = $"\"{cookie_value}\"";
request.AddParameter(cookie_key, cookie_value, ParameterType.Cookie);
}
}
// 调用示例
addRequestCookies(ref request, "item1=value1;item2=value2")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
◆ 添加参数Params
request.AddQueryParameter("ParamKey", "ParamValue");
1
◆ 添加参数Body
> form-data和x-www-form-urlencoded
request.AddParameter("FormKey", "FormValue");
1
> JSON数据
// 构建需要提交的JSON数据:{"Name": "zhangsan", "Score": [81, 92, 86]}
JObject post_json = new JObject();
post_json.Add("Name", "zhangsan");
JArray score = new JArray() { 81, 92, 86 };
post_json.Add("Score", score);
// 序列化JSON数据
string post_data = JsonConvert.SerializeObject(post_json);
// 将JSON参数添加至请求中
request.AddParameter("application/json", post_data, ParameterType.RequestBody);
1
2
3
4
5
6
7
8
9
> File上传
request.AddFile("FileKey", @"F:\Demo.txt"); // 添加文件
1
四、执行Request请求
◆ JSON结果
IRestResponse response = client.Execute(request); // 执行请求
string res_text = response.Content; // 文本结果
JObject res_json = (JObject)JsonConvert.DeserializeObject(res_text); // JSON结果
1
2
3
◆ File下载
byte[] response = client.DownloadData(request); // 执行请求
System.IO.File.WriteAllBytes(@"F:\Demo.txt", response); // 将返回结果保存到文件
1
2
★ 小技巧 ★ :
可以使用Fiddler来对比C# RestSharp发送的请求和Postman发送的请求,来测试添加的参数是否达到了同Postman一样的效果。
对于同个平台下的多个请求,可共用一个Client发送请求,减少不必要的重复设置参数。此方式也可用在存在Cookie返回的场景。
封装的AddCookies方法对于重复的Cookie键只能保留一个,例如淘宝的部分Cookie中含有两个_tb_token_参数,则需要添加代码去除掉没用的那个。
淘宝平台Sign算法
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Text;
1
2
3
public string md5(string inStr)
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] InBytes = Encoding.GetEncoding("utf-8").GetBytes(inStr);
byte[] OutBytes = md5.ComputeHash(InBytes);
string OutString = "";
for (int i = 0; i < OutBytes.Length; i++)
{
OutString += OutBytes[i].ToString("x2");
}
return OutString;
}
public string get_sign(string t, string data, string token)
{
string appKey = "12574478"; //淘宝的APPkey
string pre_sign = string.Format("{0}&{1}&{2}&{3}", token, t, appKey, data);
return md5(pre_sign);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 从Cookie中匹配Sign算法中所需的token
string token = Regex.Match(cookie, @"_m_h5_tk=\w+_").Value.Trim('_').Replace("m_h5_tk=", "");
// 获取当前时间戳(Sign算法中所需的t参数)
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
string t = (Convert.ToInt64(ts.TotalSeconds * 1000)).ToString();
// JSON data处理(Sign算法中所需的data参数)
JObject post_json = new JObject();
string data = JsonConvert.SerializeObject(post_json);
// 生成Sign
string sign = get_sign(t, data, token);
1
2
3
4
5
6
7
8
9
10

————————————————
版权声明:本文为CSDN博主「软件小哥哥QAQ」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_31025841/article/details/120448324

标签:Postman,C#,item,JSON,添加,cookie,Cookie,RestSharp,string
来源: https://www.cnblogs.com/lhxsoft/p/16144353.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有