C# RestSarp簡單使用


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);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM