本文整理汇总了C#中System.Net.CookieContainer类的典型用法代码示例。如果您正苦于以下问题:C# CookieContainer类的具体用法?C# CookieContainer怎么用?C# CookieContainer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
CookieContainer类属于System.Net命名空间,在下文中一共展示了CookieContainer类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: SendLoginData
private async Task<bool> SendLoginData(string username, string password)
{
CookieContainer cookies = await _webManager.PostData(
Constants.LOGIN_URL, string.Format(
"action=login&username={0}&password={1}",
username.Replace(" ", "+"),
WebUtility.UrlEncode(password)));
if (cookies.Count < 2)
{
return false;
}
var fixedCookieContainer = new CookieContainer();
// TODO: HUGE HACK. For some reason Windows Phone does not use the Domain Key on a cookie, but only the domain when making requests.
// Windows 8 won't break on it, but Windows Phone will, since the Domain Key and Domain are different on SA.
// We need to move this code to a more common place.
foreach (Cookie cookie in cookies.GetCookies(new Uri(Constants.COOKIE_DOMAIN_URL)))
{
var fixedCookie = new Cookie(cookie.Name, cookie.Value, "/", ".somethingawful.com");
fixedCookieContainer.Add(new Uri(Constants.COOKIE_DOMAIN_URL), fixedCookie);
}
await _localStorageManager.SaveCookie(Constants.COOKIE_FILE, cookies, new Uri(Constants.COOKIE_DOMAIN_URL));
return true;
}
开发者ID:Gluco,项目名称:AwfulMetro,代码行数:28,代码来源:AuthenticationManager.cs
示例2: Transfer
/// <summary>
/// Access specified url.
/// </summary>
/// <returns></returns>
public static TransferResult Transfer(string url, CookieContainer cookieContainer)
{
TransferResult rlt = new TransferResult();
try
{
url = ResolveUrl(url);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
if (cookieContainer != null)
{
request.CookieContainer = cookieContainer;
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
rlt.Result = reader.ReadToEnd();
rlt.ContentEncoding = reader.CurrentEncoding;
rlt.ContentType = response.ContentType;
rlt.Success = true;
}
catch (Exception ex)
{
Exceptions.LogOnly(ex);
rlt.Success = false;
}
return rlt;
}
开发者ID:mind0n,项目名称:hive,代码行数:29,代码来源:NetHelper.cs
示例3: GetPage
public string GetPage(string posturl)
{
Stream instream = null;
StreamReader sr = null;
HttpWebResponse response = null;
HttpWebRequest request = null;
Encoding encoding = Encoding.UTF8;
// 准备请求...
try
{
// 设置参数
request = WebRequest.Create(posturl) as HttpWebRequest;
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
request.AllowAutoRedirect = true;
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
//发送请求并获取相应回应数据
response = request.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才开始向目标网页发送Post请求
instream = response.GetResponseStream();
sr = new StreamReader(instream, encoding);
//返回结果网页(html)代码
string content = sr.ReadToEnd();
string err = string.Empty;
Response.Write(content);
return content;
}
catch (Exception ex)
{
string err = ex.Message;
return string.Empty;
}
}
开发者ID:K-Library-NET,项目名称:PopcornStudios,代码行数:34,代码来源:SelectMenu.aspx.cs
示例4: Post
public static HttpWebRequest Post(string url, CookieContainer cookies = null)
{
var request = CreateRequest(new Uri(url), cookies);
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/x-www-form-urlencoded";
return request;
}
开发者ID:XcodeFi,项目名称:InstagramUser,代码行数:7,代码来源:HttpRequestBuilder.cs
示例5: GetLoginUrl
public bool GetLoginUrl(string userId, string password, string dmtrackPageid, string st, ref CookieContainer cookieContainer)
{
string preUrl = "https://login.alibaba.com/validateST.htm?pd=alibaba&pageFrom=standardlogin&u_token=&xloginPassport={0}&xloginPassword={1}&xloginCheckToken=&rememberme=rememberme&runatm=runatm&dmtrack_pageid={2}&st={3}";
string url = string.Format(preUrl, userId, password, dmtrackPageid, st);
string html = HttpHelper.GetHtml(url);
string xloginCallBackForRisUrl = "https://login.alibaba.com/xloginCallBackForRisk.do";
string postString = "dmtrack_pageid_info=" + dmtrackPageid + "&xloginPassport=" + userId + "&xloginPassword=" + password + "&ua=&pd=alibaba";
HttpHelper.GetHtml(xloginCallBackForRisUrl, postString, cookieContainer);
if (string.IsNullOrEmpty(html) || html.IndexOf("var xman_success=") == -1)
{
return false;
}
string context = html.Replace("var xman_success=", "").Trim();
AliLoginUser aliLoginUser = JsonConvert.FromJson<AliLoginUser>(context);
List<string> urls = aliLoginUser.xlogin_urls;
foreach (string urlstring in urls)
{
HttpHelper.GetHtml(urlstring, cookieContainer);
}
string manageHtml = HttpHelper.GetHtml(HttpClient.ManageHtml, cookieContainer);
DataCache.Instance.CsrfToken = HttpClient.GetCsrfToken(manageHtml);
DataCache.Instance.CheckCodeUrl = HttpClient.GetCheckCodeUrl(manageHtml);
DataCache.Instance.AliID = FileUtils.GetAliId(cookieContainer, Constants.HomeUrl);
ShareCookie.Instance.LoginCookieContainer = cookieContainer;
return true;
}
开发者ID:rew170,项目名称:soomecode,代码行数:27,代码来源:Passporter.cs
示例6: Build
public IWebRequest Build(string url, IEnumerable<KeyValuePair<string, string>> headers, CookieContainer cookieContainer, bool allowAutoRedirect = true)
{
var request = WebRequest.Create(url);
var httpRequest = request as HttpWebRequest;
httpRequest.AllowAutoRedirect = allowAutoRedirect;
httpRequest.CookieContainer = cookieContainer;
foreach (var kvp in headers)
{
switch (kvp.Key.ToUpperInvariant())
{
case "HOST":
httpRequest.Host = kvp.Value;
break;
case "REFERER":
httpRequest.Referer = kvp.Value;
break;
case "USER-AGENT":
httpRequest.UserAgent = kvp.Value;
break;
case "ACCEPT":
httpRequest.Accept = kvp.Value;
break;
default:
httpRequest.Headers.Add(kvp.Key, kvp.Value);
break;
}
}
return new DesktopWebRequest(httpRequest);
}
开发者ID:CrshOverride,项目名称:CourseraDotNet,代码行数:29,代码来源:DesktopRequestBuilder.cs
示例7: PrimeDice
public PrimeDice()
{
_CC = new CookieContainer();
_CC.Add(new Cookie("user", "43579", "/", "primedice.com"));
_CC.Add(new Cookie("password", "ea1a3c", "/", "primedice.com"));
_CC.Add(new Cookie("betting", "1", "/", "primedice.com"));
}
开发者ID:KBrizzle,项目名称:PrimeDiceBot,代码行数:7,代码来源:PrimeDice.cs
示例8: ConvertToCookieContainer
/// <summary>
/// convert cookies string to CookieContainer
/// </summary>
/// <param name="cookies"></param>
/// <returns></returns>
public static CookieContainer ConvertToCookieContainer(Dictionary<string, string> cookies)
{
CookieContainer cookieContainer = new CookieContainer();
foreach (var cookie in cookies)
{
string[] strEachCookParts = cookie.Value.Split(';');
int intEachCookPartsCount = strEachCookParts.Length;
foreach (string strCNameAndCValue in strEachCookParts)
{
if (!string.IsNullOrEmpty(strCNameAndCValue))
{
Cookie cookTemp = new Cookie();
int firstEqual = strCNameAndCValue.IndexOf("=");
string firstName = strCNameAndCValue.Substring(0, firstEqual);
string allValue = strCNameAndCValue.Substring(firstEqual + 1, strCNameAndCValue.Length - (firstEqual + 1));
cookTemp.Name = firstName;
cookTemp.Value = allValue;
cookTemp.Path = "/";
cookTemp.Domain = cookie.Key;
cookieContainer.Add(cookTemp);
}
}
}
return cookieContainer;
}
开发者ID:yonglehou,项目名称:ToolRepository,代码行数:32,代码来源:Http3Helper.cs
示例9: ChencSubmitDatas
protected bool ChencSubmitDatas(CookieContainer cookieContainer, String postData)
{
var submitAction = new SubmitOrderAction();
var translation = new HTML_Translation();
submitAction.PostData = postData;
var str = submitAction.CheckOrderInfoEx(cookieContainer);
var returnString = translation.TranslationHtmlEx(str);
if (returnString["data"]["errMsg"] != null && returnString["data"]["errMsg"].ToString() != "")
{
return _checkState = false;
}
if (str.Contains("取消次数过多"))
{
return _checkState = false;
}
if (returnString["data"]["get608Msg"] != null)
{
return _checkState = false;
}
if (returnString["messages"].Any())
{
return _checkState = false;
}
return _checkState = true;
}
开发者ID:shepherds126,项目名称:12306_Helper,代码行数:25,代码来源:GetDatas_Background.cs
示例10: GetVideoUrl
public override string GetVideoUrl(string url)
{
CookieContainer cc = new CookieContainer();
string fullUrl = url + "?ss=1";
string webData = WebCache.Instance.GetWebData(fullUrl, "ss=1&sss=1", cc);
Match m = Regex.Match(webData, @"var\st=setTimeout\(""lc\('(?<s>[^']*)','(?<k>[^']*)','(?<t>[^']*)','(?<key>[^']*)'\)"",[^\)]*\);");
if (m.Success)
{
string newUrl = String.Format(@"http://www.ecostream.tv/lo/mq.php?s={0}&k={1}&t={2}&key={3}",
m.Groups["s"].Value, m.Groups["k"].Value, m.Groups["t"].Value, m.Groups["key"].Value);
webData = WebCache.Instance.GetWebData(newUrl, "", cc, referer: fullUrl);
m = Regex.Match(webData, @"<param\sname=""flashvars""\svalue=""file=(?<url>[^&]*)&[^>]*>");
if (m.Success)
{
newUrl = HttpUtility.UrlDecode(m.Groups["url"].Value);
if (!Uri.IsWellFormedUriString(newUrl, UriKind.Absolute))
{
Uri uri = null;
if (Uri.TryCreate(new Uri(url), newUrl, out uri))
{
return WebCache.Instance.GetRedirectedUrl(uri.ToString() + "&start=0");
}
}
}
}
return String.Empty;
}
开发者ID:leesanghyun2,项目名称:mp-onlinevideos2,代码行数:27,代码来源:EcoStream.cs
示例11: ExecuteHttpVerb
private static WebResponse ExecuteHttpVerb(string url, string verbData, CookieContainer cookieContainer = null, string contentType = "application/x-www-form-urlencoded", string verb = "POST")
{
try
{
WebRequest request = WebRequest.Create(url);
HttpWebRequest wr = request as HttpWebRequest;
if (cookieContainer != null)
wr.CookieContainer = cookieContainer;
wr.AllowAutoRedirect = false;
request.Method = verb;
wr.Proxy = null;
wr.UserAgent = UserAgent;
if (!string.IsNullOrEmpty(verbData))
{
byte[] byteArray = Encoding.UTF8.GetBytes(verbData);
request.ContentType = contentType;
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
}
WebResponse response = request.GetResponse();
return response;
}
catch (Exception ex)
{
throw ex;
}
}
开发者ID:BikS2013,项目名称:bUtility,代码行数:33,代码来源:WebClientHelper.cs
示例12: Meteor
public Meteor()
{
cookies = new Cookie();
cookies.Domain = "http://www.meteor.ie";
cookies.Name = "meteor";
cookieContainer = new CookieContainer();
}
开发者ID:miconico,项目名称:AIB24Base,代码行数:7,代码来源:clsMeteor.cs
示例13: 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;
}
}
}
开发者ID:fanpan26,项目名称:PzWxUtils,代码行数:34,代码来源:RequestUtility.cs
示例14: SavePostThread
public SavePostThread(CookieContainer cookie, string userAgent, List<SavedListing> posts, bool save)
{
mCookie = cookie;
mUserAgent = userAgent;
postsToSave = posts;
mSave = save;
}
开发者ID:albertonoys,项目名称:RedditSaveTransfer,代码行数:7,代码来源:SavePostThread.cs
示例15: LoginNormal
private void LoginNormal(string username,string password,string data,ref CookieContainer cookies)
{
//POST login data
Dictionary<string,string> postData = new Dictionary<string, string> ();
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create ("https://www.livecoding.tv/accounts/login/");
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705)";
request.CookieContainer = cookies;
request.Method = "POST";
request.Referer = "https://www.livecoding.tv/accounts/login/";
request.ContentType = "application/x-www-form-urlencoded";
postData.Add ("csrfmiddlewaretoken", HtmlHelper.getAttribute(HtmlHelper.getSingleElement(data,"<input type='hidden' name='csrfmiddlewaretoken'"),"value"));
postData.Add ("login", username);
postData.Add ("password", password);
byte[] postBuild = HttpHelper.CreatePostData (postData);
request.ContentLength = postBuild.Length;
request.GetRequestStream ().Write (postBuild, 0, postBuild.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse ();
using (System.IO.StreamReader sr = new System.IO.StreamReader (response.GetResponseStream ())) {
data = sr.ReadToEnd();
}
if (LoginCompleted != null)
LoginCompleted (this, cookies);
}
开发者ID:CsharpLassi,项目名称:LiveCodingChat,代码行数:26,代码来源:EmailLogin.cs
示例16: DiscoverDynamicCategories
public override int DiscoverDynamicCategories()
{
if (Settings.Categories == null) Settings.Categories = new BindingList<Category>();
cc = new CookieContainer();
string data = GetWebData(@"https://www.filmon.com/tv/live", userAgent: userAgent, cookies: cc);
string jsondata = @"{""result"":" + Helpers.StringUtils.GetSubString(data, "var groups =", @"if(!$.isArray").Trim().TrimEnd(';') + "}";
JToken jt = JObject.Parse(jsondata) as JToken;
foreach (JToken jCat in jt["result"] as JArray)
{
RssLink cat = new RssLink();
cat.Name = jCat.Value<string>("title");
cat.Description = jCat.Value<string>("description");
cat.Thumb = jCat.Value<string>("logo_uri");
Settings.Categories.Add(cat);
JArray channels = jCat["channels"] as JArray;
List<VideoInfo> videos = new List<VideoInfo>();
foreach (JToken channel in channels)
{
VideoInfo video = new VideoInfo();
video.Thumb = channel.Value<string>("logo");
video.Description = channel.Value<string>("description");
video.Title = channel.Value<string>("title");
video.VideoUrl = @"https://www.filmon.com/ajax/getChannelInfo";
video.Other = String.Format(@"channel_id={0}&quality=low", channel.Value<string>("id"));
videos.Add(video);
}
cat.Other = videos;
}
Settings.DynamicCategoriesDiscovered = true;
return Settings.Categories.Count;
}
开发者ID:leesanghyun2,项目名称:mp-onlinevideos2,代码行数:31,代码来源:FilmonUtil.cs
示例17: GetVideoUrl
public override string GetVideoUrl(VideoInfo video)
{
CookieContainer newCc = new CookieContainer();
foreach (Cookie c in cc.GetCookies(new Uri(@"https://www.filmon.com/")))
{
newCc.Add(c);
}
NameValueCollection headers = new NameValueCollection();
headers.Add("Accept", "*/*");
headers.Add("User-Agent", userAgent);
headers.Add("X-Requested-With", "XMLHttpRequest");
string webdata = GetWebData(video.VideoUrl, (string)video.Other, newCc, headers: headers);
JToken jt = JObject.Parse(webdata) as JToken;
JArray streams = jt.Value<JArray>("streams");
video.PlaybackOptions = new Dictionary<string, string>();
foreach (JToken stream in streams)
{
string serverUrl = stream.Value<string>("url");
RtmpUrl res = new RtmpUrl(serverUrl);
res.Live = true;
res.PlayPath = stream.Value<string>("name");
int p = serverUrl.IndexOf("live/?id");
res.App = serverUrl.Substring(p);
video.PlaybackOptions.Add(stream.Value<string>("quality"), res.ToString());
}
return video.PlaybackOptions.First().Value;
}
开发者ID:leesanghyun2,项目名称:mp-onlinevideos2,代码行数:32,代码来源:FilmonUtil.cs
示例18: GetCheckCodeImageStream
//用于获取验证码图像的方法
public Stream GetCheckCodeImageStream(string imageAddress, CookieContainer ccEntered, out CookieCollection ccReturned)
{
HttpWebRequest request;
HttpWebResponse response;
request = (HttpWebRequest)HttpWebRequest.Create(imageAddress);
request.Method = "GET";
request.ProtocolVersion = HttpVersion.Version11;
//request.Connection = "keep-alive";
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.861.0 Safari/535.2";
request.Accept = "*/*";
request.Referer = "http://buy.taobao.com/auction/buy_now.jhtml";
//request.Headers.Add("Connection", "keep-alive");
request.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
request.Headers.Add("Accept-Language", "zh-CN,zh;q=0.8");
request.Headers.Add("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
request.CookieContainer = ccEntered;
request.AllowAutoRedirect = true;
response = (HttpWebResponse)request.GetResponse();
ccReturned = response.Cookies;
Stream s = response.GetResponseStream();
response.Close();
return s;
}
开发者ID:KublaikhanGeek,项目名称:Taobao-Auction,代码行数:31,代码来源:AuctionOperations.cs
示例19: PrepareWebRequest
protected override HttpWebRequest PrepareWebRequest()
{
this.UserName.CheckStringIsNullOrEmpty("UserName");
string password = this.Password;
if (password == null)
password = string.Empty;
string md5Password = Common.GetMd5String(password).ToLower();
string padata = "username=" + HttpUtility.UrlEncode(this.UserName) + "&pwd=" + HttpUtility.UrlEncode(md5Password) + "&imgcode=&f=json";
string url = "https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN";
CookieContainer cc = new CookieContainer();//接收缓存
byte[] byteArray = Encoding.UTF8.GetBytes(padata); // 转化
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); //新建一个WebRequest对象用来请求或者响应url
request.CookieContainer = cc; //保存cookie
request.Method = "POST"; //请求方式是POST
request.ContentType = "application/x-www-form-urlencoded"; //请求的内容格式为application/x-www-form-urlencoded
request.ContentLength = byteArray.Length;
request.Referer = "https://mp.weixin.qq.com/";
request.UserAgent = "Mozilla/5.0 (Windows NT 5.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1";
request.Headers["X-Requested-With"] = "XMLHttpRequest";
using (Stream newStream = request.GetRequestStream()) //返回用于将数据写入 Internet 资源的 Stream。
{
newStream.Write(byteArray, 0, byteArray.Length); //写入参数
}
return request;
}
开发者ID:jerryshi2007,项目名称:AK47Source,代码行数:33,代码来源:WeChatLoginExecutor.cs
示例20: GetWebPageAsync
/// <summary>
/// Coockieを使用してHTMLを取得する
/// </summary>
/// <param name="uri">取得先のURL</param>
/// <param name="cc">取得済みのCoockie</param>
/// <returns>htmlソース</returns>
async Task<string> GetWebPageAsync(Uri uri, CookieContainer cookie)
{
// Cookieがnullでなければ使用する
using (var handler = (cookie != null ?
new HttpClientHandler() { CookieContainer = cookie } :
new HttpClientHandler()))
using (var client = new HttpClient(handler))
{
client.Timeout = TimeSpan.FromSeconds(10.0);
try
{
return await client.GetStringAsync(uri);
}
catch (HttpRequestException e)
{
// 404エラーや、名前解決失敗など
Console.WriteLine("\n例外発生!");
// InnerExceptionも含めて、再帰的に例外メッセージを表示する
Exception ex = e;
while (ex != null)
{
Console.WriteLine("例外メッセージ: {0} ", ex.Message);
ex = ex.InnerException;
}
}
catch (TaskCanceledException e)
{
Console.WriteLine("\nタイムアウト!");
Console.WriteLine("例外メッセージ: {0} ", e.Message);
}
return null;
}
}
开发者ID:TK-R,项目名称:MoneyForwardScraping,代码行数:40,代码来源:MFLib.cs
注:本文中的System.Net.CookieContainer类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论