一、导入命名空间
using RestSharp;
using Newtonsoft.Json; // 用于JSON序列化/反序列化
using Newtonsoft.Json.Linq; // 用于构建JSON对象
二、构建客户端
◆ 创建客户端对象
RestClient client = new RestClient();
◆ 设置当前URL
client.BaseUrl = new Uri("https://www.baidu.com/s");
◆ 设置响应超时
client.Timeout = -1; // 永不超时
◆ 添加默认Header
client.AddDefaultHeader("HeaderKey", "HeaderValue");
◆ 添加单项Cookie
client.AddDefaultParameter("itemKey", "itemValue", ParameterType.Cookie);
◆ 添加多项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")
三、构建请求
◆ 创建请求对象
RestRequest request = new RestRequest(Method.GET); // Post请求:Method.POST
◆ 添加参数Header
request.AddHeader("HeaderKey", "HeaderValue");
◆ 添加单项Cookie
request.AddParameter("itemName", "itemValue", ParameterType.Cookie);
◆ 添加多项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")
◆ 添加参数Params
request.AddQueryParameter("ParamKey", "ParamValue");
◆ 添加参数Body
> form-data和x-www-form-urlencoded
request.AddParameter("FormKey", "FormValue");
> 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);
> File上传
request.AddFile("FileKey", @"F:\Demo.txt"); // 添加文件
四、执行Request请求
◆ JSON结果
IRestResponse response = client.Execute(request); // 执行请求
string res_text = response.Content; // 文本结果
JObject res_json = (JObject)JsonConvert.DeserializeObject(res_text); // JSON结果
◆ File下载
byte[] response = client.DownloadData(request); // 执行请求
System.IO.File.WriteAllBytes(@"F:\Demo.txt", response); // 将返回结果保存到文件
★ 小技巧 ★ :
- 可以使用Fiddler来对比C# RestSharp发送的请求和Postman发送的请求,来测试添加的参数是否达到了同Postman一样的效果。
- 对于同个平台下的多个请求,可共用一个Client发送请求,减少不必要的重复设置参数。此方式也可用在存在Cookie返回的场景。
- 封装的AddCookies方法对于重复的Cookie键只能保留一个,例如淘宝的部分Cookie中含有两个_tb_token_参数,则需要添加代码去除掉没用的那个。
淘宝平台Sign算法
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Text;
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);
}
// 从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);