一、导入命名空间
using RestSharp;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
二、构建客户端
◆ 创建客户端对象
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);
◆ 添加参数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数据
JObject post_json = new JObject();
post_json.Add("Name", "zhangsan");
JArray score = new JArray() { 81, 92, 86 };
post_json.Add("Score", score);
string post_data = JsonConvert.SerializeObject(post_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);
◆ 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";
string pre_sign = string.Format("{0}&{1}&{2}&{3}", token, t, appKey, data);
return md5(pre_sign);
}
string token = Regex.Match(cookie, @"_m_h5_tk=\w+_").Value.Trim('_').Replace("m_h5_tk=", "");
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
string t = (Convert.ToInt64(ts.TotalSeconds * 1000)).ToString();
JObject post_json = new JObject();
string data = JsonConvert.SerializeObject(post_json);
string sign = get_sign(t, data, token);