private void LoadImages() { string url = $"https://api.instagram.com/v1/users/{userid}/media/recent/?access_token={access_token}&COUNT=10"; System.Net.HttpWebRequest request = System.Net.HttpWebRequest.CreateHttp(url); request.BeginGetResponse((iar) => { try { System.Net.WebResponse response = ((System.Net.HttpWebRequest)iar.AsyncState).EndGetResponse(iar); var responseStream = response.GetResponseStream(); var data = (JObject)JObject.ReadFrom(new JsonTextReader(new StreamReader(responseStream))); responseStream.Dispose(); var sb = new StringBuilder(); foreach (var item in (JArray)data["data"]) { var img = (string)item["images"]["standard_resolution"]["url"]; sb.Append(img); sb.Append(","); } sb.Length--; OnImagesLoad?.Invoke(this, sb.ToString()); } catch { InvokeFail(); } }, request); }
public void Start() { string url = $"https://www.instagram.com/{username}/?__a=1"; System.Net.HttpWebRequest request = System.Net.HttpWebRequest.CreateHttp(url); request.BeginGetResponse((iar) => { try { System.Net.WebResponse response = ((System.Net.HttpWebRequest)iar.AsyncState).EndGetResponse(iar); var responseStream = response.GetResponseStream(); var data = (JObject)JObject.ReadFrom(new JsonTextReader(new StreamReader(responseStream))); responseStream.Dispose(); userid = (string)data["user"]["id"]; Device.BeginInvokeOnMainThread(() => { StartBrowser(); }); } catch { InvokeFail(); } }, request); }
public static void CheckVersion() { try { System.Net.HttpWebRequest req = System.Net.WebRequest.CreateHttp(string.Format("http://babelua.duapp.com/version")); req.Timeout = 1000; req.BeginGetResponse((ir) => { var resp = req.EndGetResponse(ir); Version latest_version, local_version; using (var reader = new StreamReader(resp.GetResponseStream())) { latest_version = new Version(reader.ReadToEnd()); } local_version = new Version(SettingConstants.Version.Substring(2)); System.Diagnostics.Debug.Print("latest version: " + latest_version + "local version: " + local_version); if (latest_version > local_version) { UpdateVersionGuide(local_version, latest_version); } }, null); } catch { } }
/// <summary> /// 下载图片 /// </summary> private void DownloadImg(int id, string url, string needReferer) { try { System.Net.HttpWebRequest req = System.Net.WebRequest.Create(url) as System.Net.HttpWebRequest; reqs.Add(id, req); req.Proxy = MainWindow.WebProxy; req.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"; if (needReferer != null) { //req.Referer = url.Substring(0, url.IndexOf('/', 7) + 1); req.Referer = needReferer; } req.AllowAutoRedirect = true; //异步下载开始 req.BeginGetResponse(new AsyncCallback(RespCallback), new KeyValuePair <int, System.Net.HttpWebRequest>(id, req)); } catch (Exception ex) { Program.Log(ex, "Download sample failed"); StopLoadImg(id); } }
private void SearchEntry_SelectedItemChanged(object sender, SelectedItemChangedEventArgs e) { var placeId = placeList[(string)e.SelectedItem]; string url = "https://maps.googleapis.com/maps/api/place/details/xml?placeid={0}&key=AIzaSyCEIQNsuPwizWAWUuC68d1RJNONXXFAQlI"; url = string.Format(url, placeId); System.Net.HttpWebRequest request = System.Net.HttpWebRequest.CreateHttp(url); request.BeginGetResponse((iar) => { Device.BeginInvokeOnMainThread(() => { this.searchEntry.ShowHideListbox(false); this.searchEntry.ForceLayout(); }); System.Net.WebResponse response = ((System.Net.HttpWebRequest)iar.AsyncState).EndGetResponse(iar); var xmlDoc = System.Xml.Linq.XDocument.Load(response.GetResponseStream()); var xmlRoot = (System.Xml.Linq.XElement)xmlDoc.FirstNode; if (xmlRoot.Element("status").Value.Equals("OK")) { var loc = xmlRoot.Element("result").Element("geometry").Element("location"); Location = new GeoCoordinate(double.Parse(loc.Element("lat").Value, Utils.EnCulture), double.Parse(loc.Element("lng").Value, Utils.EnCulture)); OnSelected?.Invoke(this, Location); } }, request); this.searchEntry.ForceLayout(); }
public void getImageFromUrl(string url) { System.Net.HttpWebRequest request = null; System.Net.HttpWebResponse response = null; request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); request.Method = "GET"; request.BeginGetResponse(Response_Completed, request); }
public void UpdateUserData(string type) { try { System.Net.HttpWebRequest req = System.Net.WebRequest.CreateHttp(string.Format("http://babelua.duapp.com/user.php?type={0}&guid={1}&version={2}", type, BabePackage.Setting.UserGUID, SettingConstants.Version)); req.Method = "POST"; req.ContentLength = 0; req.Timeout = 1000; req.BeginGetResponse(null, null); System.Diagnostics.Debug.Print("send user data:" + type); } catch { } }
void UploadLog() { UpdateUserData("run"); try { string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), SettingConstants.SettingFolder, SettingConstants.ErrorLogFile); if (File.Exists(path)) { StreamReader reader = new StreamReader(path, new UTF8Encoding(false)); byte[] dat = UTF8Encoding.UTF8.GetBytes("data=" + reader.ReadToEnd()); reader.Dispose(); System.Net.HttpWebRequest req = System.Net.WebRequest.CreateHttp("http://babelua.duapp.com/"); req.Method = "POST"; req.ContentLength = dat.Length; req.ContentType = "application/x-www-form-urlencoded"; var resstream = req.GetRequestStream(); resstream.Write(dat, 0, dat.Length); resstream.Dispose(); req.Timeout = 3000; req.BeginGetResponse((ar) => { var resp = req.EndGetResponse(ar) as System.Net.HttpWebResponse; byte[] buf = new byte[resp.ContentLength]; var respstream = resp.GetResponseStream(); respstream.Read(buf, 0, buf.Length); respstream.Dispose(); if (buf.Length == 1 && buf[0] == 49) { File.Delete(path); } resp.Close(); }, null); } } catch { } }
private static void MakeRequestJson(string method, string body, Action <ResponseDataJson> callback) { System.Net.HttpWebRequest request = System.Net.HttpWebRequest.CreateHttp(API_URL + method); request.ContentType = "text/json"; request.Accept = "text/json"; request.Method = "POST"; request.BeginGetRequestStream((iar) => { try { var reqStream = ((System.Net.HttpWebRequest)iar.AsyncState).EndGetRequestStream(iar); System.IO.StreamWriter writer = new System.IO.StreamWriter(reqStream); writer.Write(body); writer.Flush(); request.BeginGetResponse((iar2) => { var isOk = false; try { var response = ((System.Net.HttpWebRequest)iar.AsyncState).EndGetResponse(iar2); var responseStream = response.GetResponseStream(); var jsonStr = new System.IO.StreamReader(responseStream).ReadToEnd(); responseStream.Dispose(); isOk = true; callback.Invoke(new ResponseDataJson(ResponseCode.OK, jsonStr)); } catch (Exception e) { if (!isOk) { callback.Invoke(new ResponseDataJson(ResponseCode.Fail, null, e)); } } }, request); } catch (Exception e) { callback.Invoke(new ResponseDataJson(ResponseCode.Fail, null, e)); } }, request); }
private void SearchEntry_TextChanged(object sender, TextChangedEventArgs e) { if (searchEntry.Text.Length < 2) { return; } string url = "https://maps.googleapis.com/maps/api/place/autocomplete/xml?input={0}&types=address&components=country:ng&key=AIzaSyCEIQNsuPwizWAWUuC68d1RJNONXXFAQlI"; url = string.Format(url, searchEntry.Text); System.Net.HttpWebRequest request = System.Net.HttpWebRequest.CreateHttp(url); request.BeginGetResponse((iar) => { System.Net.WebResponse response = ((System.Net.HttpWebRequest)iar.AsyncState).EndGetResponse(iar); var xmlDoc = System.Xml.Linq.XDocument.Load(response.GetResponseStream()); var xmlRoot = (System.Xml.Linq.XElement)xmlDoc.FirstNode; if (xmlRoot.Element("status").Value.Equals("OK")) { lock (placeList) { placeList.Clear(); foreach (var item in xmlRoot.Elements("prediction")) { var text = item.Element("description").Value; var placeId = item.Element("place_id").Value; if (!placeList.ContainsKey(text)) { placeList.Add(text, placeId); } } Device.BeginInvokeOnMainThread(() => { ShowSearchResult(); }); } } }, request); }
public void send(object o) { var args = o as Jint.Native.Object.ObjectInstance; options = extractOptions(args); url = new Uri(origin + options["url"]); if (options["transport"] == "browser") { req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); } else { req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); req.CookieContainer = cookieContainer; // disable buffering (this only works for ClientHttp version) //_req.AllowWriteStreamBuffering = false; // causes silent crash on Mac OS X 10.8.x } req.Method = options["method"]; // add custom headers if (headers.Count != 0) { foreach (string key in headers.Keys) { if (headers[key] == null) { continue; } switch (key.ToLower()) { // in silverlight 3, these are set by the web browser that hosts the Silverlight application. // http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest%28v=vs.95%29.aspx case "connection": case "content-length": case "expect": case "if-modified-since": case "referer": case "transfer-encoding": case "user-agent": break; // in silverlight this isn't supported, can not find reference to why not case "range": break; // in .NET Framework 3.5 and below, these are set by the system. // http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest%28v=VS.90%29.aspx case "date": case "host": break; case "accept": req.Accept = (string)headers[key]; break; case "content-type": req.ContentType = headers[key]; break; default: req.Headers[key] = (string)headers[key]; break; } } } req.ContentLength = 0; { req.ContentType = options["mimeType"]; } if (req.ContentLength == 0) { req.BeginGetResponse(new AsyncCallback(responseCallback), req); } else { req.BeginGetRequestStream(new AsyncCallback(responseCallback), req); } }
/// <summary> /// 下载图片 /// </summary> public void DownloadImg() { if (PreFetcher.Fetcher.PreFetchedImg(img.PreviewUrl) != null) { preview.Source = PreFetcher.Fetcher.PreFetchedImg(img.PreviewUrl); //preview.Source = BitmapDecoder.Create(PreFetcher.Fetcher.PreFetchedImg(img.PreUrl), BitmapCreateOptions.None, BitmapCacheOption.OnLoad).Frames[0]; } else { try { req = System.Net.WebRequest.Create(img.PreviewUrl) as System.Net.HttpWebRequest; req.Proxy = MainWindow.WebProxy; req.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"; if (needReferer != null) //req.Referer = img.PreUrl.Substring(0, img.PreUrl.IndexOf('/', 7) + 1); req.Referer = needReferer; //异步下载开始 req.BeginGetResponse(new AsyncCallback(RespCallback), req); } catch (Exception ex) { Program.Log(ex, "Start download preview failed"); StopLoadImg(); } } if (!isDetailSucc && img.DownloadDetail != null) { isRetrievingDetail = true; chk.Text = "信息加载中..."; System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback((o) => { try { img.DownloadDetail(img, MainWindow.WebProxy); Dispatcher.Invoke(new VoidDel(() => { LayoutRoot.IsEnabled = true; ShowImgDetail(); isRetrievingDetail = false; if (imgLoaded && ImgLoaded != null) ImgLoaded(index, null); })); } catch (Exception ex) { Program.Log(ex, "Download img detail failed"); Dispatcher.Invoke(new VoidDel(() => { isRetrievingDetail = false; canRetry = true; chk.Text = "信息加载失败"; if (imgLoaded && ImgLoaded != null) ImgLoaded(index, null); })); } })); } }
/// <summary> /// Begins an asynchronous request to an Internet resource. /// </summary> /// <param name="callback"></param> /// <param name="state"></param> /// <returns></returns> public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state) { return(_httpWebRequest.BeginGetResponse(callback, state)); }
private void button2_Click(object sender, EventArgs e) { System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("http://www.cnblogs.com"); IAsyncResult asyncResult = request.BeginGetResponse(requestCompleted, request); }
/// <summary> /// 下载图片 /// </summary> public void DownloadImg() { if (PreFetcher.Fetcher.PreFetchedImg(img.PreviewUrl) != null) { preview.Source = PreFetcher.Fetcher.PreFetchedImg(img.PreviewUrl); //preview.Source = BitmapDecoder.Create(PreFetcher.Fetcher.PreFetchedImg(img.PreUrl), BitmapCreateOptions.None, BitmapCacheOption.OnLoad).Frames[0]; } else { try { req = System.Net.WebRequest.Create(img.PreviewUrl) as System.Net.HttpWebRequest; req.Proxy = MainWindow.WebProxy; req.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"; if (needReferer != null) { //req.Referer = img.PreUrl.Substring(0, img.PreUrl.IndexOf('/', 7) + 1); req.Referer = needReferer; } //异步下载开始 req.BeginGetResponse(new AsyncCallback(RespCallback), req); } catch (Exception ex) { Program.Log(ex, "Start download preview failed"); StopLoadImg(); } } if (!isDetailSucc && img.DownloadDetail != null) { isRetrievingDetail = true; chk.Text = "信息加载中..."; System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback((o) => { try { img.DownloadDetail(img, MainWindow.WebProxy); Dispatcher.Invoke(new VoidDel(() => { LayoutRoot.IsEnabled = true; ShowImgDetail(); isRetrievingDetail = false; if (imgLoaded && ImgLoaded != null) { ImgLoaded(index, null); } })); } catch (Exception ex) { Program.Log(ex, "Download img detail failed"); Dispatcher.Invoke(new VoidDel(() => { isRetrievingDetail = false; canRetry = true; chk.Text = "信息加载失败"; if (imgLoaded && ImgLoaded != null) { ImgLoaded(index, null); } })); } })); } }
/// <summary> /// Validação do usuário no webservice do cliente /// </summary> /// <param name="usu">Objeto Usuário carregado do autenticador</param> /// <returns>Enum LoginStatus: 0 [Sucesso] ou 5[Erro]</returns> public static LoginStatus ValidaUsuarioWebService(SYS_Usuario usu) { LoginStatus status = LoginStatus.Sucesso; var result = string.Empty; #region string envelope = @"<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:ser='http://www.w3.org/1999/XMLSchema-instance'>" + "<soapenv:Body>" + "<ser:AuthenticateJAAS>" + "<user>?</user>" + "<password>?</password>" + "<encryption>0</encryption>" + "<parameters>" + "<!--Optional:-->" + "<flowInstanceID>?</flowInstanceID>" + "<!--Optional:-->" + "<flowName>?</flowName>" + "<!--Optional:-->" + "<pmEncrypted>?</pmEncrypted>" + "<!--Optional:-->" + "<pmUserName>" + usu.usu_login.ToString() + "</pmUserName>" + "<!--Optional:-->" + "<pmUserPassword>" + usu.usu_senha.ToString() + "</pmUserPassword>" + "</parameters>" + "</ser:AuthenticateJAAS>" + "</soapenv:Body>" + "</soapenv:Envelope>"; #endregion try { string wsReturn = string.Empty; //string url = "http://*****:*****@"text/xml;charset=""utf-8"""; webRequest.Accept = "text/xml"; webRequest.Method = "POST"; using (System.IO.Stream stream = webRequest.GetRequestStream()) { soapEnvelopeXml.Save(stream); } IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null); asyncResult.AsyncWaitHandle.WaitOne(); string soapResult; string retornoWebService = string.Empty; using (System.Net.WebResponse webResponse = webRequest.EndGetResponse(asyncResult)) { using (System.IO.StreamReader rd = new System.IO.StreamReader(webResponse.GetResponseStream())) { soapResult = rd.ReadToEnd(); XmlDocument xml = new XmlDocument(); xml.LoadXml(soapResult); //XmlNodeList xnList = xml.GetElementsByTagName("AuthenticateJAASResponse"); //XmlNodeList xnList = xml.GetElementsByTagName("AuthenticateJAASResult"); XmlNodeList xnList = xml.GetElementsByTagName("pmLogged"); foreach (XmlNode xn in xnList) { retornoWebService = xn.InnerText; } } } if (!String.IsNullOrEmpty(retornoWebService)) { status = SalvarSenhaUsuario(usu, retornoWebService); } else { status = LoginStatus.Erro; } } else { status = LoginStatus.Erro; } } catch (Exception e) { status = LoginStatus.Erro; } return(status); }