簡體   English   中英

使用 RestSharp 保存 cookie

[英]Saving a cookie with RestSharp

我正在嘗試使用 RestSharp 在 WinPhone 7 Mango 的 RestClients 和應用程序會話之間獲取一個 cookie。

如果我使用單個 RestClient 實例,則 cookie 會持續存在。 我希望 cookie 在 RestClient 實例和用戶返回應用程序之間持續存在。

RestSharp 最近添加了自動 cookie 支持!

RestSharp 102.4+ 支持對來自同一個 IRestClient 的所有請求使用共享的 System.Net.CookieContainer。 通過這樣做,響應中設置或取消設置的任何 cookie 都將在后續請求中使用。 為了使用共享的 CookieContainer,只需在使用前設置 RestClient 實例的屬性:

var client = new RestClient ("http://server/");
client.CookieContainer = new System.Net.CookieContainer();

文檔:https://github.com/restsharp/RestSharp/wiki/Cookies

必須對 Cookie 值進行編碼。

if ( header["Set-Cookie"] != null )
{
string value = header["Set-Cookie"];

Encoding iso = Encoding.GetEncoding("iso-8859-9");//may be utf-8

value = HttpUtility.UrlEncode(value, iso);
Cookie moCookie = new Cookie( "Cookie", value);
moCookie.Domain = GatewayURI.Trim();
CookieContainer CommCookie = new CookieContainer();
CommCookie.Add( moCookie );
request.CookieContainer = CommCookie;
}

您需要手動保存 cookie 信息,RestSharp 中不支持在會話之間保存 cookie。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM