public static void Main(string[] args) { string videoID = "2FlgVN03fNM"; string[] itagByPriority = { "5", "6", "34", "35" }; string videoUrl = "https://www.youtube.com/get_video_info?asv=3&el=detailpage&hl=en_US&video_id=" + videoID; string encodedVideo = null; using (WebClient client = new WebClient()) { encodedVideo = client.DownloadString(videoUrl); } NameValueCollection video = HttpUtility.ParseQueryString(encodedVideo); NameValueCollection preferredStream = video["url_encoded_fmt_stream_map"]. Split(new char[] { ',' }). Select(encodedStream => HttpUtility.ParseQueryString(encodedStream)). OrderBy(stream => Array.IndexOf(itagByPriority, stream["itag"])). LastOrDefault(); if (preferredStream != null) { Console.WriteLine("{0}&signature={1}", preferredStream["url"], preferredStream["sig"]); } }
public void FillBlogEntry(product p) { // init values for activity message productid = p.id; productname = p.title; subdomainid = p.subdomainid; producturl = p.ToProductUrl(); blogEntry.Title.Text = productname; blogEntry.Content = new AtomContent(); var productpage = hostName.ToDomainUrl(p.ToProductUrl()); StringBuilder sb = new StringBuilder(); sb.Append("<div xmlns='http://www.w3.org/1999/xhtml'>"); sb.AppendFormat("<h3><a target='_blank' href='{0}'>{1}</a></h3>", productpage, HttpUtility.HtmlEncode(productname)); if (p.sellingPrice.HasValue) { var currency = p.MASTERsubdomain.currency.ToCurrency(); var sellingPrice = p.tax.HasValue ? (p.sellingPrice.Value * (p.tax.Value / 100 + 1)).ToString("n" + currency. decimalCount) : p.sellingPrice.Value.ToString("n" + currency.decimalCount); if (p.specialPrice.HasValue) { // if has special price then original (strike-through) + special price var specialPrice = p.tax.HasValue ? (p.specialPrice.Value * (p.tax.Value / 100 + 1)).ToString("n" + currency. decimalCount) : p.specialPrice.Value.ToString("n" + currency.decimalCount); sb.AppendFormat( "<h3><span style='text-decoration:line-through;'>{2}{0}</span><span style='margin-left:10px;'>{2}{1}</span></h3>", sellingPrice, specialPrice, currency.symbol); } else { sb.AppendFormat("<h3><span>{1}{0}</span></h3>", sellingPrice, currency.symbol); } } sb.Append("<p>"); sb.Append(HttpUtility.HtmlEncode(p.details).ToHtmlBreak()); sb.Append("</p>"); sb.Append("<p><a target='_blank' href='"); sb.Append(productpage); sb.Append("'>Go to product page</a></p>"); sb.Append("</div>"); blogEntry.Content.Content = sb.ToString(); blogEntry.Content.Type = "xhtml"; blogEntry.Authors.Add(new AtomPerson()); blogEntry.Authors[0].Name = p.MASTERsubdomain.organisation.users.First().ToFullName(); blogEntry.Authors[0].Email = p.MASTERsubdomain.organisation.users.First().email; }
/// <summary> /// 构造Get请求 /// </summary> static HttpWebRequest _BuildGetRequest(string url, RequestParams data, Action <HttpWebRequest> action) { //如果传入了data,则先构造请求url if (data != null && data.Count > 0) { StringBuilder sb = new StringBuilder(url); if (url.IndexOf('?') < 0) { sb.Append('?'); } //build request foreach (var entry in data) { object v = entry.Value; sb.Append(HttpHelper.UrlEncode(entry.Key)) .Append('=') .Append(v == null ? "" : HttpHelper.UrlEncode(v.ToString())) .Append('&'); } //change url url = sb.ToString(0, sb.Length - 1); //remove last '&' } HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.Method = "GET"; action?.Invoke(req); return(req); }
/// <summary> /// OAuth/WXLogin?referer= /// 转到这里进行授权 /// </summary> /// <param name="referer"></param> /// <returns></returns> public ActionResult WXLogin(string referer = null) { //静默模式登陆 string toUrl = string.Format(baseUrl + "BaseCallback?referer={0}", HttpUtility.UrlEncode(referer ?? "/")); string url = OAuthApi.GetAuthorizeUrl(appId, toUrl, STATE, OAuthScope.snsapi_base); return(Redirect(url)); }
private static StatsPackage GetStatsPackage(DataServicePackage package) { return(new StatsPackage { Id = package.Id, Version = package.Version, DownloadCount = package.DownloadCount, // Workaround for the gallery url until it is fixed. Url = String.Format("http://nuget.org/List/Packages/{0}/{1}", HttpUtility.UrlPathEncode(package.Id), HttpUtility.UrlPathEncode(package.Version.ToString())) }); }
public URLBuilder(string businessEmail, string successUrl, string cancelUrl, string notifyUrl, string clientEmail, Invoice invoice) { URLUtility = new HttpUtility(); this.businessEmail = businessEmail; this.clientEmail = clientEmail; this.cancelUrl = cancelUrl; this.successUrl = successUrl; this.notifyUrl = notifyUrl; this.invoiceNo = invoice.InvoiceNo; this.invoice = invoice; }
public URLBuilder(System.Web.SessionState.HttpSessionState Session, string businessEmail, string successUrl, string cancelUrl, string notifyUrl, string clientEmail, int invoiceNo) { URLUtility = new HttpUtility(); this.businessEmail = businessEmail; this.clientEmail = clientEmail; this.Session = Session; this.cancelUrl = cancelUrl; this.successUrl = successUrl; this.notifyUrl = notifyUrl; this.invoiceNo = invoiceNo; }
public Contacts FetchContacts() { var o = new OAuthBase(); var nonce = OAuthBase.GenerateNonce(); var timestamp = OAuthBase.GenerateTimeStamp(); var sig = OAuthBase.GenerateSignature(new Uri(url), OAuthClient.OAUTH_YAHOO_CONSUMER_KEY, OAuthClient.OAUTH_YAHOO_CONSUMER_SECRET, oauth_token, oauth_secret, "GET", timestamp, nonce); sig = HttpUtility.UrlEncode(sig); var sb = new StringBuilder(); sb.Append(url); sb.AppendFormat("&oauth_consumer_key={0}", OAuthClient.OAUTH_YAHOO_CONSUMER_KEY); sb.AppendFormat("&oauth_nonce={0}", nonce); sb.AppendFormat("&oauth_timestamp={0}", timestamp); sb.AppendFormat("&oauth_version={0}", "1.0"); sb.AppendFormat("&oauth_signature_method={0}", "HMAC-SHA1"); sb.AppendFormat("&oauth_signature={0}", sig); sb.AppendFormat("&oauth_token={0}", HttpUtility.UrlEncode(oauth_token)); string content = ""; WebResponse response; try { var request = WebRequest.Create(sb.ToString()); response = request.GetResponse(); using (StreamReader sr = new StreamReader(response.GetResponseStream())) { content = sr.ReadToEnd(); } } catch (WebException ex) { response = ex.Response; if (response != null) { using (var sr = new StreamReader(response.GetResponseStream())) { var error = sr.ReadToEnd(); Syslog.Write(sb + " " + error); } } return(null); } var serializer = new JavaScriptSerializer(); var result = serializer.Deserialize <ContactsResult>(content); return(result.contacts); }
public static string Build(IReadOnlyCollection <KeyValuePair <string, string> >?source) #endif { if (source == null || source.Count == 0) { return(""); } var sb = new StringBuilder(source.Count * 32); foreach (var kv in source) { sb.Append('&'); sb.Append(WebUtility.UrlEncode(kv.Key)); sb.Append('='); sb.Append(WebUtility.UrlEncode(kv.Value)); } return(sb.ToString(1, sb.Length - 1)); }
static int _CreateSystem_Web_HttpUtility(IntPtr L) { try { int count = LuaDLL.lua_gettop(L); if (count == 0) { System.Web.HttpUtility obj = new System.Web.HttpUtility(); ToLua.PushSealed(L, obj); return(1); } else { return(LuaDLL.luaL_throw(L, "invalid arguments to ctor method: System.Web.HttpUtility.New")); } } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
public ActionResult DoLogin(string phone, string userPwd, int id = 0, string token = "", string tourl = "") { UserBll userApi = new UserBll(); PublicUserModel user = new PublicUserModel(); if (!string.IsNullOrEmpty(token)) { user = userApi.PublicUserLoginByToken(token); } else { user = userApi.PublicUserLogin(phone, userPwd, 1, id); } if (user != null && user.UserID > 0) { String saveKey = System.Configuration.ConfigurationManager.AppSettings["AuthSaveKey"]; if (String.IsNullOrEmpty(saveKey)) { saveKey = "WXLoginedUser"; } Session[saveKey] = user; HttpCookie loginUserCookie = new HttpCookie(saveKey, CryptoUtility.TripleDESEncrypt(user.UserID.ToString())); loginUserCookie.Expires = DateTime.Now.AddDays(10); HttpContext.Response.Cookies.Add(loginUserCookie); if (!string.IsNullOrEmpty(tourl)) { return(new RedirectResult(HttpUtility.UrlDecode(tourl))); } return(Json(new { status = 0 }, JsonRequestBehavior.AllowGet)); } if (!string.IsNullOrEmpty(tourl)) { return(new RedirectResult("/m/u/login")); } return(Json(new { status = 1, msg = "用户名或者密码错误" }, JsonRequestBehavior.AllowGet)); }
/// <summary> /// 构造Post请求 (x-www-form-urlencoded) /// </summary> static HttpWebRequest _BuildPostRequest(string url, RequestParams data, Action <HttpWebRequest> action) { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; action?.Invoke(req); //写入数据 if (data != null && data.Count > 0) { //Build request using (StreamWriter writer = new StreamWriter(req.GetRequestStream())) { bool first = true; foreach (var entry in data) { if (!first) { writer.Write('&'); } else { first = false; } object v = entry.Value; writer.Write(HttpHelper.UrlEncode(entry.Key)); writer.Write('='); if (v != null) { writer.Write(HttpHelper.UrlEncode(v.ToString())); } } } } return(req); }
/// <summary> /// 静默模式 /// </summary> /// <param name="code"></param> /// <param name="state"></param> /// <returns></returns> public ActionResult BaseCallback(string code, string state) { if (string.IsNullOrEmpty(code)) { return(Content("您拒绝了授权!")); } if (state != STATE) { //这里的state其实是会暴露给客户端的,验证能力很弱,这里只是演示一下 //实际上可以存任何想传递的数据,比如用户ID,并且需要结合例如下面的Session["OAuthAccessToken"]进行验证 return(Content("验证失败!请从正规途径进入!")); } //通过,用code换取access_token var result = OAuthApi.GetAccessToken(appId, secret, code); if (result.errcode != ReturnCode.请求成功) { return(Content("错误:" + result.errmsg)); } //下面2个数据也可以自己封装成一个类,储存在数据库中(建议结合缓存) //如果可以确保安全,可以将access_token存入用户的cookie中,每一个人的access_token是不一样的 Session["OAuthAccessTokenStartTime"] = DateTime.Now; Session["OAuthAccessToken"] = result; //判断用户是否存存 string userId = null; try { userId = GetUserIdByOpenId(result.openid); } catch (Exception ex) { } if (userId == null) { //因为这里还不确定用户是否关注本微信,所以只能试探性地获取一下 OAuthUserInfo userInfo = null; try { if (ReqietTryGetUser) { //已关注,可以得到详细信息 userInfo = OAuthApi.GetUserInfo(result.access_token, result.openid); } if (string.IsNullOrEmpty(Request["referer"])) { ViewData["ByBase"] = true; return(View("UserInfoCallback", userInfo)); } else { } } catch (ErrorJsonResultException ex) { //未关注,只能授权,无法得到详细信息 //这里的 ex.JsonResult 可能为:"{\"errcode\":40003,\"errmsg\":\"invalid openid\"}" //return Content("用户已授权,授权Token:" + result); } if (userInfo != null && result.openid == userInfo.openid && userInfo.nickname != null) { userId = RegisterUser(result.openid, userInfo); } } string referer = Request["referer"] ?? "/"; if (userId == null) { //授权登陆 string toUrl = string.Format(baseUrl + "UserInfoCallback?referer={0}", HttpUtility.UrlEncode(referer)); string url = OAuthApi.GetAuthorizeUrl(appId, toUrl, STATE, OAuthScope.snsapi_userinfo); return(Redirect(url)); } else { if (!LoginByUserId(userId)) { return(Content("登陆失败 userId:" + userId)); } //登陆用户 return(RedirectToUrl(referer)); } }