[英]Unable to send cookies with RestSharp
我一直在嘗試使用幾種不同的方法在 Windows 電話上訪問基於 REST 的 API,但我似乎遇到了將 cookies 附加到所有請求的問題。 我已經嘗試過WebClient
方法(現在似乎已標記為 SecurityCritical,因此您不能再從它繼承並添加代碼)。 我簡要地看了看HttpWebRequest
,它充其量看起來很麻煩。
現在我正在使用看起來不錯的 RestSharp,但是我的 cookies 在發送時未添加到請求中仍然存在問題。
我的代碼如下:
// ... some additional support vars ...
private RestClient client;
public ClassName() {
client = new RestClient();
client.BaseUrl = this.baseAddress.Scheme + "://" + baseAddress.DnsSafeHost;
}
public void GetAlbumList()
{
Debug.WriteLine("Init GetAlbumList()");
if (this.previousAuthToken == null || this.previousAuthToken.Length == 0)
{
throw new MissingAuthTokenException();
}
RestRequest request = new RestRequest(this.baseUrl, Method.GET);
// Debug prints the correct key and value, but it doesnt seem to be included
// when I run the request
Debug.WriteLine("Adding cookie [" + this.gallerySessionIdKey + "] = [" + this.sessionId + "]");
request.AddParameter(this.gallerySessionIdKey, this.sessionId, ParameterType.Cookie);
request.AddParameter("g2_controller", "remote:GalleryRemote", ParameterType.GetOrPost);
request.AddParameter("g2_form[cmd]", "fetch-albums-prune", ParameterType.GetOrPost);
request.AddParameter("g2_form[protocol_version]", "2.2", ParameterType.GetOrPost);
request.AddParameter("g2_authToken", this.previousAuthToken, ParameterType.GetOrPost);
// Tried adding a no-cache header in case there was some funky caching going on
request.AddHeader("cache-control", "no-cache");
client.ExecuteAsync(request, (response) =>
{
parseResponse(response);
});
}
如果有人對為什么沒有將 cookies 發送到服務器有任何提示,請告訴我:) 我使用的是 RestSharp 101.3 和 .Net 4。
RestSharp 102.4 似乎已經解決了這個問題。
request.AddParameter(_cookie_name, _cookie_value, ParameterType.Cookie);
或者,在你的情況下
request.AddParameter(this.gallerySessionIdKey, this.sessionId, ParameterType.Cookie);
會正常工作。
我遇到了同樣的問題,幾個小時后我嘗試了:
request.AddParameter()
request.AddHeader("Cookie", Cookie value);
and another ways, finnally the solution was using:
request.AddCookie(cookie name, cookie value);
request.AddCookie(cookie name, cookie value);
我希望這可以解決問題。
HttpWebRequest 是最好用的。 只需使用 CookieContainer 即可使用 cookies。 但是您必須在所有請求中保留 CookieContainer 的引用才能完成這項工作
CookieContainer cc = new CookieContainer();
HttpWebRequest webRequest = HttpWebRequest.CreateHttp(uri);
webRequest.CookieContainer = cc;
webRequest.BeginGetResponse((callback)=>{//Code on callback},webRequest);
cc 必須在您的實例中引用才能在其他請求中重用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.