C#使用postman框架发送请求
GET请求在使用RestSharp时不产生响应,但在Postman中获得响应
为什么postman发出的请求可以正常响应但是C#就不行
postman中post请求正常,但是利用postman生成C#后台http模拟代码之后调用失败问题记录
postman中post请求正常,但是利用postman生成C#后台代码无响应
为什么它在Postman中可以工作,而在我的C#代码中却不能?
var url = string.Format("https://www.huakai2018.com/play/{0}-{1}{2}.html", id, xianlu, ep);
var htmlText = "";
Sharing.setTips("动漫id已发出请求...");
//htmlText= excutecmd(url); 没代理不能访问
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var client = new RestClient(url);
client.Timeout = -1;
var request = new RestRequest(Method.GET);
request.AddHeader("Authorization", "Bearer tokenComesHere");
IRestResponse response = client.Execute(request);
htmlText = response.Content;
var client = new RestClient("https://dplayer.m3u8list.top/API.php");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AlwaysMultipartFormData = true;
request.AddParameter("url", "+5dKJoevc4o1KuIlaSNVC/T08pHymQhL6L/TjxddMXT2G+eJDZVBxvuwRD5HnMzFjmFX9l65twY064Co4nw2zU/0zQFhLPuHdIIuvxNFAp0=");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
post加请求头
var client2 = new RestClient("https://dplayer.m3u8list.top/API.php");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AlwaysMultipartFormData = true;
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
//request.AddHeader("Content-Length", "application/x-www-form-urlencoded");
request.AddHeader("Host", "dplayer.m3u8list.top");
request.AddHeader("Accept", "*/*");
request.AddHeader("Accept-Encoding", "gzip, deflate, br");
request.AddHeader("Connection", "keep-alive");
request.AddHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; QQDownload 718; .NET CLR 2.0.50727)");
request2.AddParameter("url", jiamim3u8url);
IRestResponse response2 = client.Execute(request);
Console.WriteLine(response2.Content);
var client2 = new RestClient("https://dplayer.m3u8list.top/API.php");
client2.Timeout = -1;
var request2 = new RestRequest(Method.POST);
request2.AlwaysMultipartFormData = true;
request.AddHeader("Content-Length", "128");
request.AddHeader("Host", "dplayer.m3u8list.top");
request.AddHeader("Accept", "application / json, text / javascript, */*; q=0.01");
request.AddHeader("Accept-Encoding", "gzip, deflate, br, zstd");
request.AddHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
request.AddHeader("Origin", "https://dplayer.m3u8list.top");
request.AddHeader("Priority", "u = 1, i");
request.AddHeader("Connection", "keep-alive");
request.AddHeader("User-Agent", "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Mobile Safari/537.36 Edg/126.0.0.0");
request2.AddHeader("Content-Type", "application/x-www-form-urlencoded");
//request2.AddHeader("Content-Length", "application/x-www-form-urlencoded");
request2.AddHeader("Host", "dplayer.m3u8list.top");
request2.AddHeader("Accept", "*/*");
request2.AddHeader("Accept-Encoding", "gzip, deflate, br");
request2.AddHeader("Connection", "keep-alive");
request2.AddHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; QQDownload 718; .NET CLR 2.0.50727)");
跨线层更新ui 类定义
public static void setlinks(string TipsText)
{
Widget.LinkLabel.Invoke(Form1.txtlinklabel, new object[]
{
Widget.LinkLabel,
TipsText + "\n"
});
} 先在widget中定义 public static LinkLabel LinkLabel;
然后在form1中定义 public static Form1.Linklabel_Delegate txtlinklabel;
再定义 public delegate string Linklabel_Delegate(LinkLabel textThis, string caption);
然后在初始化的时候绑定 定义 Form1.txtlinklabel = new Form1.Linklabel_Delegate(this.textSetlink);
然后在方法里面更新ui
public string textSetlink(LinkLabel textThis, string caption)
{
try
{
if (caption != null)
{
linkLabel1txt.Text=caption;
}
else
{
caption = linkLabel1txt.Text;
}
}
catch (Exception ex)
{
Sharing.WriteBug(string.Format("发生位置:编辑框置标题或取标题,原因:{0}", ex.Message));
}
return caption;
}
还需要在initialization中绑定控件
private void initialization()
{
try
{
Widget.List = this.doubleBufferListView1;
Widget.MenuStrip = this.contextMenuStrip1;
Widget.start = this.button_Analysis;
Widget.TipsBox = this.textBox4;
Widget.LinkLabel = this.linkLabel1txt;
C# 使用RestSharp实现Postman中的各种形式的请求
一、导入命名空间 二、构建客户端 ◆ 创建客户端对象 ◆ 设置当前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对象 二、构建客户端 ◆ 创建客户端对象 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 = $""""; client.AddDefaultParameter(cookie_key, cookie_value, ParameterType.Cookie); } } // 调用示例 addClientCookies(ref client, "item1=value1;item2=value2") 三、构建请求 ◆ 创建请求对象 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 = $""""; 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"); // 添加文件 1 四、执行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);
问答
string pattern = @"写从player_aaa*到<script>然后获取里面的url";
Match match = Regex.Match(htmlText, pattern);修改代码用一个正则从html的 player_aaaa 中提取 url
从请求的字符串中找到url_next":"https:\/\/v11.tlkqc.com\/wjv11\/202403\/29\/SCAuHxhNpx3\/video\/index.m3u8" 先匹配urlnext然后取出https的链接 string pattern = @" 先匹配urlnext然后取出https的链接"; Match match = Regex.Match(htmlText, pattern);修改代码用一个正则从html的 url_next中提取 url
string pattern = @"var player_aaaa=(.*?)</script>";
Match match = Regex.Match(htmlText, pattern, RegexOptions.Singleline);
if (match.Success)
{
string jsonContent = match.Groups[1].Value;
// 解析 JSON
JObject jsonObject = JObject.Parse(jsonContent);
// 提取 url 字段
m3u8url = (string)jsonObject["url"];
以什么开头再以什么结尾直接定位
C#请求返回的字符串怎么删除里面的转义字符 删除 C# 请求返回字符串中的转义字符,您可以使用 Regex.Unescape 方法。该方法可将转义字符还原为原始字符。
string responseString = "This is a string with escape characters: \u0022Hello, World!\u0022";
string unescapedString = Regex.Unescape(responseString);