本文整理汇总了C#中System.Net.CookieContainer.GetCookies方法的典型用法代码示例。如果您正苦于以下问题:C# CookieContainer.GetCookies方法的具体用法?C# CookieContainer.GetCookies怎么用?C# CookieContainer.GetCookies使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.CookieContainer
的用法示例。
在下文中一共展示了CookieContainer.GetCookies方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: HttpGet
/// <summary>
/// 使用Get方法获取字符串结果(加入Cookie)
/// </summary>
/// <param name="url"></param>
/// <param name="cookieContainer"></param>
/// <param name="encoding"></param>
/// <returns></returns>
public static string HttpGet(string url, CookieContainer cookieContainer = null, Encoding encoding = null, int timeOut = App.AppRequestTimeOut)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.Timeout = timeOut;
if (cookieContainer != null)
{
request.CookieContainer = cookieContainer;
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (cookieContainer != null)
{
response.Cookies = cookieContainer.GetCookies(response.ResponseUri);
}
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader myStreamReader = new StreamReader(responseStream, encoding ?? Encoding.GetEncoding("utf-8")))
{
string retString = myStreamReader.ReadToEnd();
return retString;
}
}
}
示例2: GetCookies_AddCookiesWithImplicitDomain_CookiesReturnedOnlyForExactDomainMatch
public void GetCookies_AddCookiesWithImplicitDomain_CookiesReturnedOnlyForExactDomainMatch()
{
const string SchemePrefix = "http://";
const string OriginalDomain = "contoso.com";
var container = new CookieContainer();
var cookie1 = new Cookie(CookieName1, CookieValue1);
var cookie2 = new Cookie(CookieName2, CookieValue2) { Version = 1 };
var uri = new Uri(SchemePrefix + OriginalDomain);
container.Add(uri, cookie1);
container.Add(uri, cookie2);
var cookies = container.GetCookies(uri);
Assert.Equal(2, cookies.Count);
Assert.Equal(OriginalDomain, cookies[CookieName1].Domain);
Assert.Equal(OriginalDomain, cookies[CookieName2].Domain);
uri = new Uri(SchemePrefix + "www." + OriginalDomain);
cookies = container.GetCookies(uri);
Assert.Equal(0, cookies.Count);
uri = new Uri(SchemePrefix + "x.www." + OriginalDomain);
cookies = container.GetCookies(uri);
Assert.Equal(0, cookies.Count);
uri = new Uri(SchemePrefix + "y.x.www." + OriginalDomain);
cookies = container.GetCookies(uri);
Assert.Equal(0, cookies.Count);
uri = new Uri(SchemePrefix + "z.y.x.www." + OriginalDomain);
cookies = container.GetCookies(uri);
Assert.Equal(0, cookies.Count);
}
示例3: GetCookies_AddCookieVersion0WithExplicitDomain_CookieReturnedForDomainAndSubdomains
public void GetCookies_AddCookieVersion0WithExplicitDomain_CookieReturnedForDomainAndSubdomains()
{
const string SchemePrefix = "http://";
const string OriginalDomain = "contoso.com";
var container = new CookieContainer();
var cookie1 = new Cookie(CookieName1, CookieValue1) { Domain = OriginalDomain };
container.Add(new Uri(SchemePrefix + OriginalDomain), cookie1);
var uri = new Uri(SchemePrefix + OriginalDomain);
var cookies = container.GetCookies(uri);
Assert.Equal(1, cookies.Count);
Assert.Equal(OriginalDomain, cookies[CookieName1].Domain);
uri = new Uri(SchemePrefix + "www." + OriginalDomain);
cookies = container.GetCookies(uri);
Assert.Equal(1, cookies.Count);
uri = new Uri(SchemePrefix + "x.www." + OriginalDomain);
cookies = container.GetCookies(uri);
Assert.Equal(1, cookies.Count);
uri = new Uri(SchemePrefix + "y.x.www." + OriginalDomain);
cookies = container.GetCookies(uri);
Assert.Equal(1, cookies.Count);
uri = new Uri(SchemePrefix + "z.y.x.www." + OriginalDomain);
cookies = container.GetCookies(uri);
Assert.Equal(1, cookies.Count);
}
示例4: GetResponse
/// <summary>
/// 请求指定的URL,返回Response对象 注意:在Asp.Net页面Post的时候要加入__VIEWSTATE、__EVENTVALIDATION数据
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="postData">post提交时的数据内容(a=1&b=2) 注意:post内容的值要url encode编码</param>
/// <param name="SetHeaderAction">
/// 设置请求头的信息
/// 如:ContentType 、ContentLength 、Method 等
/// 默认设置的头:KeepAlive=true; AllowAutoRedirect=false; request.ContentType = "application/x-www-form-urlencoded";
/// </param>
/// <returns>返回带Cookie对象的Response对象</returns>
public static HttpWebResponse GetResponse(string url, string postData = null, Action<HttpWebRequest> SetHeaderAction = null)
{
HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
#region 默认的request头信息
CookieContainer cc = new CookieContainer();
request.CookieContainer = cc;
request.KeepAlive = true;
request.AllowAutoRedirect = false;
request.ContentType = "application/x-www-form-urlencoded";
#endregion
#region 自定义头部信息
if (SetHeaderAction != null)
SetHeaderAction(request);
#endregion
#region 如果是post提交的话,写入提交的数据到流中
if (request.Method == "POST")
{
postData = postData ?? string.Empty;
var bytes = Encoding.UTF8.GetBytes(postData);
request.ContentLength = bytes.Length;
var stream = request.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
stream.Flush();
stream.Close();
}
#endregion
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
response.Cookies = cc.GetCookies(new Uri(url));
return response;
}
示例5: VerifyAndPass
public async Task VerifyAndPass(LogInLayout LIlayout, string userName, CookieContainer cookieJar,
bool saveCredentials, ContentPageController viewController)
{
CookieJar = cookieJar;
// store credientials if it is a new login
if (saveCredentials)
{
//Gather Cookie String
var gameUri = new Uri(Constants.EndPoint);
var gamecookies = CookieJar.GetCookies(gameUri);
string CookieString = null;
foreach (Cookie c in gamecookies)
{
if (c.Name == ".AspNet.ApplicationCookie") CookieString = c.Value;
}
//Store Cookie
AuthCache.InsertObject(userName, CookieString);
}
//just preps the Game Manager
GameManager.SetupGame(CookieJar, ViewController);
if (!SeenHomeScreen)
{
SeenHomeScreen = true;
var HLayout = new HomeLayout(ViewController, true);
}
else
{
var GSlayout = new GameSelectLayout(ViewController);
}
}
示例6: RequestAsync
private async void RequestAsync()
{
NCookie ncookie = new NCookie();
ncookie.Refere = "http://scholar.google.com";
ncookie.LastestRequestTime = DateTime.Now;
CookieContainer cookiecontainer = new CookieContainer();
using (HttpClientHandler httpclienthandler = new HttpClientHandler() { CookieContainer = cookiecontainer })
using (HttpClient httpclient = new HttpClient(httpclienthandler))
{
httpclient.DefaultRequestHeaders.Add("Accept", "text/html, application/xhtml+xml, */*");
httpclient.DefaultRequestHeaders.Add("Accept-Language", "zh-Hans-CN,zh-Hans;q=0.8,en-US;q=0.5,en;q=0.3");
httpclient.DefaultRequestHeaders.Add("User-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
httpclient.DefaultRequestHeaders.Add("Host", "scholar.google.com");
httpclient.DefaultRequestHeaders.Add("DNT", "1");
httpclient.DefaultRequestHeaders.Add("Connection", "Keep-Alive");
string url = "http://scholar.google.com";
HttpResponseMessage response = await httpclient.GetAsync(url);
Uri uri = new Uri(url);
var cookies = cookiecontainer.GetCookies(uri).Cast<Cookie>();
foreach (var cookie in cookies)
{
ncookie.Cookies.Add(cookie.Name, cookie.Value);
}
}
lock (obj)
{
NCookies.Add(ncookie);
}
}
示例7: SendRequest
protected static Response SendRequest(string request)
{
string requestBase = String.Format("http://localhost:{0}/", 8080);
if (request.StartsWith("/")) request = request.Substring(1);
CookieContainer cookies = new CookieContainer();
var handler = new HttpClientHandler{CookieContainer = cookies};
var client = new HttpClient(handler);
var fullRequest = new Uri(requestBase + request);
var response = client.GetAsync(fullRequest);
bool connected = response.Wait(TimeSpan.FromSeconds(2));
connected.Should().BeTrue();
response.Result.StatusCode.Should().Be(HttpStatusCode.OK);
var body = response.Result.Content.ReadAsStringAsync();
body.Wait();
string bodyText = body.Result;
return new Response(){
Body = bodyText,
Cookies = cookies.GetCookies(fullRequest),
};
}
示例8: reset
/// <summary>
/// 重启路由
/// </summary>
private string reset(string url, string userName, string password, string method, string data)
{
CookieContainer container = new CookieContainer();
string requestUriString = url;
if (method == "GET") requestUriString += "?" + data;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUriString);
request.Method = method;
if (method == "POST") {
byte[] POSTData = new UTF8Encoding().GetBytes(data);
request.ContentLength = POSTData.Length;
request.GetRequestStream().Write(POSTData, 0, POSTData.Length);
}
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0;CIBA)";
request.CookieContainer = container;
request.KeepAlive = true;
request.Accept = "*/*";
request.Timeout = 3000;
request.PreAuthenticate = true;
CredentialCache cache = new CredentialCache();
cache.Add(new Uri(requestUriString), "Basic", new NetworkCredential(routeInfo.UserName, routeInfo.RPassword));
request.Credentials = cache;
try {
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
response.Cookies = container.GetCookies(request.RequestUri);
new StreamReader(response.GetResponseStream(), Encoding.Default).Close();
response.Close();
return string.Empty;
} catch (Exception ex) {
return ex.Message;
}
}
示例9: GetPlaybackOptions
public override Dictionary<string, string> GetPlaybackOptions(string url)
{
Dictionary<string, string> playbackOptions = new Dictionary<string, string>();
CookieContainer cc = new CookieContainer();
string data = GetWebData(url, cookies: cc, cache: false);
Regex rgx = new Regex(@"""metadataUrl"":""(?<url>[^""]*)");
Match m = rgx.Match(data);
if (m.Success)
{
JObject json = GetWebData<JObject>(m.Groups["url"].Value, cookies: cc, cache: false);
JToken videos = json["videos"];
if (videos != null)
{
foreach(JToken video in videos)
{
string key = video["key"].Value<string>();
string videoUrl = video["url"].Value<string>();
MPUrlSourceFilter.HttpUrl httpUrl = new MPUrlSourceFilter.HttpUrl(videoUrl);
CookieCollection cookies = cc.GetCookies(new Uri("http://my.mail.ru"));
httpUrl.Cookies.Add(cookies);
playbackOptions.Add(key, httpUrl.ToString());
}
}
}
playbackOptions = playbackOptions.OrderByDescending((p) =>
{
string resKey = p.Key.Replace("p","");
int parsedRes = 0;
int.TryParse(resKey, out parsedRes);
return parsedRes;
}).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
return playbackOptions;
}
示例10: MyGetWebData
private CookieContainer MyGetWebData(string url, string postData, CookieContainer cc)
{
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; // turn on automatic decompression of both formats so we can say we accept them
request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate"); // we accept compressed content
request.CookieContainer = cc;
request.Accept = "*/*";
request.UserAgent = OnlineVideoSettings.Instance.UserAgent;
byte[] data = Encoding.UTF8.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
request.ProtocolVersion = HttpVersion.Version10;
Stream requestStream = request.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
request.AllowAutoRedirect = false;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { };//just to get the cookies
CookieContainer result = new CookieContainer();
foreach (Cookie cookie in cc.GetCookies(new Uri("https://tmp.tweakers.net")))
{
cookie.Domain = new Uri(baseUrl).Host;
result.Add(cookie);
}
return result;
}
示例11: ConvertCookies
public static List<KeyValuePair<string, string>> ConvertCookies(CookieContainer cont)
{
List<KeyValuePair<string,string>> cookieList = new List<KeyValuePair<string, string>> ();
foreach (Cookie c in cont.GetCookies(new System.Uri("https://www.livecoding.tv")))
cookieList.Add (new KeyValuePair<string,string>(c.Name, c.Value));
return cookieList;
}
示例12: GetWebFormWithHttpRequestHelperWithCookies
public void GetWebFormWithHttpRequestHelperWithCookies()
{
CookieContainer cookies = new CookieContainer();
Uri requestUri = NormalizeUri("TestWebFormCookies1.aspx");
HttpRequestHelper.Get(requestUri, null, cookies);
CookieCollection mycookies = cookies.GetCookies(requestUri);
Cookie cookie = mycookies["Cooookie"];
Assert.IsNotNull(cookie);
Assert.AreEqual("TestWebFormCookies1", cookie.Value);
requestUri = NormalizeUri("TestWebFormCookies2.aspx");
HttpRequestHelper.Get(requestUri, null, cookies);
mycookies = cookies.GetCookies(requestUri);
cookie = mycookies["Cooookie"];
Assert.IsNotNull(cookie);
Assert.AreEqual("TestWebFormCookies2", cookie.Value);
}
示例13: LogIn
private static async Task<string> LogIn(string user, string password)
{
var cookies = new CookieContainer();
var handler = new HttpClientHandler { CookieContainer = cookies };
var client = new HttpClient(handler);
client.DefaultRequestHeaders.Authorization = new BasicAuthenticationHeaderValue(user, password);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("X-Api-Version", "1");
var sitUri = GetSituatorWebApiUrl();
var url = sitUri + "/" + "api/Login";
//string url = GetBaseAddress() + "/" + "api/Login";
var response = await client.PostAsync(url, null);
if (!response.IsSuccessStatusCode) return string.Empty;
var responseCookies = cookies.GetCookies(sitUri).Cast<Cookie>();
foreach (var cookie in responseCookies)
{
if (cookie.Name == "session-token")
{
return cookie.Value;
}
}
return string.Empty;
}
示例14: Login
public async Task<bool> Login(CancellationToken cancellationToken = default(CancellationToken))
{
if (IsLoogedIn)
return true;
var getConfigJob = ConfigurationService.GetClientConfig();
var credentialsStr = Configuration.Username + ":" + Configuration.Password;
var credentials64Str = Convert.ToBase64String(Encoding.UTF8.GetBytes(credentialsStr));
var authUri = new Uri((await getConfigJob).ApiConfig.BaseUrl,
_apiUri.Replace("{username}", Configuration.Username));
var authRequest = await CreateRequest(authUri);
authRequest.Method = HttpMethod.Post;
authRequest.Headers.Authorization = new AuthenticationHeaderValue("Basic", credentials64Str);
var response = await SendRequest(authRequest);
var cookies = new CookieContainer();
cookies.SetCookies(authUri, String.Join(", ",response.Headers.GetValues("Set-Cookie")));
SessionId = cookies.GetCookies(new Uri("http://gpodder.net"))["sessionid"];
#if DEBUG
// if (SessionId != null)
//Console.WriteLine("Authenticated");
#endif
return true;
}
示例15: OpenIE
public static void OpenIE(CookieContainer _cookieContainer)
{
foreach (Cookie cookie in _cookieContainer.GetCookies(new Uri(Properties.Resources.loginAction_login)))
{
InternetSetCookie("https://" + cookie.Domain.ToString(), cookie.Name.ToString(), cookie.Value.ToString() + ";expires=Sun,22-Feb-2099 00:00:00 GMT");
}
System.Diagnostics.Process.Start("iexplore.exe", Properties.Resources.ostweb);
}