C# 使用RestSharp 实现Get,Post 请求(2)
今天又重新测试了一下该库,的确很好用,当初为了快捷使用了Python应用,绕了一些。
查看网络实际使用的请求方式,如下图:
封装一个POST请求的方法:
static string PostBySap(string sap)
{
string url = "http://192.168.0.122:3311/UIHandler/ItemQueryHandle.ashx";
using (var client = new RestClient(url))
{
string data = $"action=query&ItemCode={sap}&Plant=&Desc_CH=&Item_Group=&page=1&rows=30";
var request = new RestRequest();
request.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
request.AddHeader("Referer", "http://192.168.0.122:3311/ItemQuery.aspx");
request.AddStringBody(data, DataFormat.None);
var response = client.PostAsync(request);
var result = response.Result.Content;
return result;
}
}
传入一个变量数据,返回响应的内容,测试OK。
封装一个Get请求:
static void GetBySAP(string sap, Language language)
{
string url = "http://192.168.0.122:8011/api/Item/Gets?";
string data = "";
switch (language)
{
case Language.Chinese:
data = $"Item_Code_SAP={sap}&&Plant_SAP=6000&EN_CH=CH";
break;
case Language.English:
data = $"Item_Code_SAP={sap}&&Plant_SAP=6000&EN_CH=EN";
break;
case Language.German:
data = $"Item_Code_SAP={sap}&&Plant_SAP=6000&EN_CH=DE";
break;
}
using (var client = new RestClient(url + data))
{
var request = new RestRequest();
request.Method = Method.Get;
request.Timeout = 3000;
var response = client.Execute(request);
var result = response.Content;
Console.WriteLine(result);
Console.ReadLine();
}
}
返回Get 请求的响应字符串,测试OK。