C# RestSarp簡單使用
阿新 • • 發佈:2020-07-09
1.簡介
RestSharp 是一個基於 .NET 框架的 REST 客戶端,RestSharp 是一個輕量的,不依賴任何第三方的元件或者類庫的 HTTP 元件,C#使用RestSharp可以快速完成http的網路請求。
2.RestSharp用法
1) 通過請求服務的地址初始化一個RestClient類
string serverUrl="127.0.0.1:8080" RestClient client = new RestClient(serverUrl);
2)傳送get或者post請求(此次請求一個測試登入的頁面,密碼使用了md5加密)
//頁面請求連結為“http://127.0.0.1:8080/test/test.html” string requestUrl="test/test.do" RestRequest request = new RestRequest(url, Method.POST); request.AddParameter("username", username); request.AddParameter("userpwd", md5(password)); IRestResponse response = client.Execute(request); IList<RestResponseCookie> cookies = response.Cookies;
3)給request新增cookies
由於RestSharp沒有會話保持,通過client.Execute每次發起的請求都不攜帶cookies資訊,當我們需要某些操作是需要保持頁面session時我們就需要給request請求中新增已經獲取的cookies,具體程式碼如下
IList<RestSharpCookie> cookies=response.Cookies; foreach (RestResponseCookie cookie in cookies) { request.AddCookie(cookie.Name, cookie.Value); } return request;
這樣我們就會給需要的reqeust新增上了cookie
4)帶json引數並且返回json的post請求
a)是簡單的引數時
可以直接用request.AddParameter(key,value)的形式傳入
b)引數是一個類時
class Datas { public string username; public string password; public Datas(string uesrname, string password) { this.username = username; this.password = password; } }//此次為了方便舉例寫了一個簡單的類其他的類物件都可以按下面方法完成 Datas data=new Datas("零度熱冰","ldrb"); StringBuilder sb = new StringBuilder(); JavaScriptSerializer json = new JavaScriptSerializer();//使用了System.Web.Script.Serialization.JavaScriptSerializer json.Serialize(data, sb); request.AddJsonBody(sb); //...........
5)將返回的引數反序列化為類物件
JavaScriptSerializer json = new JavaScriptSerializer(); Datas data=json.Deserialize<Datas>(response.Content);