public UploadStringTaskAsync ( System address, string data ) : System.Threading.Tasks.Task |
||
address | System | |
data | string | |
리턴 | System.Threading.Tasks.Task |
public async void Register(UtsData data) { string json = JsonConvert.SerializeObject(data); Log.Info("Register", json); // Request Address of the API string url = Server.url + "api/student/register"; String result = null; using (WebClient wc = new WebClient()) { wc.Headers[HttpRequestHeader.ContentType] = "application/json; charset=utf-8"; wc.Headers.Add("AppKey", "66666"); result = await wc.UploadStringTaskAsync(new Uri(url), json); Log.Info("Register SUCCESS", result); HomeController loginController = new HomeController(); await loginController.login(data.StudentId); } }
public async Task<string> GetAuthenticationData(Dictionary<string, string> authenticationFields) { string username = authenticationFields[Field_Username]; string password = authenticationFields[Field_Password]; using (WebClient client = new WebClient()) { client.Headers.Set("Content-Type", "application/json"); client.Headers.Add(HttpRequestHeader.Authorization, $"Basic {Base64Encode(username + ":" + password)}"); string json = await client.UploadStringTaskAsync($"{BitlyBaseUrl}/oauth/access_token", $"grant_type=password&username={username}&password={password}"); if (json.StartsWith("{")) { json = json.Replace(@"""data"": [ ], ", string.Empty); JsonResponse data = JsonConvert.DeserializeObject<JsonResponse>(json); if (data.status_txt == "OK") { return data.data.url; } else { throw new Exception(data.status_txt); } } else { return json; } } }
public async Task <string> DeleteAsync(WebHeaderCollection headers, string address, string data) { System.Net.WebClient client = new System.Net.WebClient { Headers = headers, CachePolicy = new HttpRequestCachePolicy() }; client.Headers["UserAgent"] = _userAgent; try { return(await client.UploadStringTaskAsync(address, "DELETE", data)); } catch (WebException e) { EsiModel returned = BuildException(e, null, null, address, data); if (returned != null) { return(string.Empty); } throw; } }
public async void SendNotification(string channelURI, string payload, NotificationType type = NotificationType.Raw) { if (WNSAuthentication.Instance.oAuthToken.AccessToken != null && !WNSAuthentication.Instance.IsRefreshInProgress) { using (var client = new WebClient()) { SetHeaders(type, client); try { await client.UploadStringTaskAsync(new Uri(channelURI), payload); } catch (WebException webException) { if (webException?.Response != null) HandleError(((HttpWebResponse)webException.Response).StatusCode, channelURI, payload); Debug.WriteLine(String.Format("Failed WNS authentication. Error: {0}", webException.Message)); } catch (Exception) { HandleError(HttpStatusCode.Unauthorized, channelURI, payload); } } } else { StoreNotificationForSending(channelURI, payload); } }
async public Task SendEvent() { using (var client = new WebClient()) { client.Headers[HttpRequestHeader.ContentType] = "application/json"; await client.UploadStringTaskAsync(sseUri, "POST", JsonConvert.SerializeObject(this)); /* exception handling? what would we even do... try { result = (await client.UploadStringTaskAsync(new Uri(url), "POST", json)); } catch (WebException exception) { string responseText; if (exception.Response != null) { var responseStream = exception.Response.GetResponseStream(); if (responseStream != null) { using (var reader = new StreamReader(responseStream)) { responseText = reader.ReadToEnd(); Debug.WriteLine(responseText); } } } } */ } }
public void RSPEC_WebClient(string address, Uri uriAddress, byte[] data, NameValueCollection values) { System.Net.WebClient webclient = new System.Net.WebClient(); // All of the following are Questionable although there may be false positives if the URI scheme is "ftp" or "file" //webclient.Download * (...); // Any method starting with "Download" webclient.DownloadData(address); // Noncompliant webclient.DownloadDataAsync(uriAddress, new object()); // Noncompliant webclient.DownloadDataTaskAsync(uriAddress); // Noncompliant webclient.DownloadFile(address, "filename"); // Noncompliant webclient.DownloadFileAsync(uriAddress, "filename"); // Noncompliant webclient.DownloadFileTaskAsync(address, "filename"); // Noncompliant webclient.DownloadString(uriAddress); // Noncompliant webclient.DownloadStringAsync(uriAddress, new object()); // Noncompliant webclient.DownloadStringTaskAsync(address); // Noncompliant // Should not raise for events webclient.DownloadDataCompleted += Webclient_DownloadDataCompleted; webclient.DownloadFileCompleted += Webclient_DownloadFileCompleted; webclient.DownloadProgressChanged -= Webclient_DownloadProgressChanged; webclient.DownloadStringCompleted -= Webclient_DownloadStringCompleted; //webclient.Open * (...); // Any method starting with "Open" webclient.OpenRead(address); // ^^^^^^^^^^^^^^^^^^^^^^^^^^^ {{Make sure that this http request is sent safely.}} webclient.OpenReadAsync(uriAddress, new object()); // Noncompliant webclient.OpenReadTaskAsync(address); // Noncompliant webclient.OpenWrite(address); // Noncompliant webclient.OpenWriteAsync(uriAddress, "STOR", new object()); // Noncompliant webclient.OpenWriteTaskAsync(address, "POST"); // Noncompliant webclient.OpenReadCompleted += Webclient_OpenReadCompleted; webclient.OpenWriteCompleted += Webclient_OpenWriteCompleted; //webclient.Upload * (...); // Any method starting with "Upload" webclient.UploadData(address, data); // Noncompliant webclient.UploadDataAsync(uriAddress, "STOR", data); // Noncompliant webclient.UploadDataTaskAsync(address, "POST", data); // Noncompliant webclient.UploadFile(address, "filename"); // Noncompliant webclient.UploadFileAsync(uriAddress, "filename"); // Noncompliant webclient.UploadFileTaskAsync(uriAddress, "POST", "filename"); // Noncompliant webclient.UploadString(uriAddress, "data"); // Noncompliant webclient.UploadStringAsync(uriAddress, "data"); // Noncompliant webclient.UploadStringTaskAsync(uriAddress, "data"); // Noncompliant webclient.UploadValues(address, values); // Noncompliant webclient.UploadValuesAsync(uriAddress, values); // Noncompliant webclient.UploadValuesTaskAsync(address, "POST", values); // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // Should not raise for events webclient.UploadDataCompleted += Webclient_UploadDataCompleted; webclient.UploadFileCompleted += Webclient_UploadFileCompleted; webclient.UploadProgressChanged -= Webclient_UploadProgressChanged; webclient.UploadStringCompleted -= Webclient_UploadStringCompleted; webclient.UploadValuesCompleted -= Webclient_UploadValuesCompleted; }
public async Task Delete(string storageKey) { var uri = _uriFormatter.FormatUri(storageKey); _logger.Debug("Deleting blob {0} from {1}", storageKey, uri); using (var webClient = new WebClient()) { await webClient.UploadStringTaskAsync(uri, "DELETE", ""); } }
private async static Task<string> PostRequest(string url) { using (var client = new WebClient()) { client.Headers.Add("user-agent", "my own code"); client.Headers.Add("content-type", "x-www-form-urlencoded"); return await client.UploadStringTaskAsync(url, "test=value"); } }
public static async Task<string> ApiProcessAsync(string method, string parameter) { using (WebClient wc = new WebClient()) { wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; wc.Encoding = System.Text.Encoding.UTF8; return await wc.UploadStringTaskAsync(new Uri(Param.ApiUrl + method), parameter + "&apiKey=" + Param.ApiKey); } }
public async Task<string> CallServer(string path, object postData) { EnsureInitialized(); string url = $"{BASE_URL}:{BasePort}/{path.ToLowerInvariant()}"; using (WebClient client = new WebClient()) { return await client.UploadStringTaskAsync(url, JsonConvert.SerializeObject(postData)); } }
private async Task<string> mput(string topic, IEnumerable<string> messages) { var path = string.Format("{0}/mput?topic={1}", baseUriString, topic); var data = string.Join("\n", messages); using (var http = new WebClient()) { var resp = await http.UploadStringTaskAsync(path, "POST", data); return resp; } }
private async Task<string> put(string topic, string message) { var path = string.Format("{0}/put?topic={1}", baseUriString, topic); var data = message; using (var http = new WebClient()) { var resp = await http.UploadStringTaskAsync(path, "POST", data); return resp; } }
public async Task Delete(string storageKey) { if (storageKey == null) throw new ArgumentNullException("storageKey"); var uri = _uriFormatter.FormatUri(storageKey); _logger.Debug("Deleting blob {0} from {1}", storageKey, uri); using (var webClient = new WebClient()) { await webClient.UploadStringTaskAsync(uri, "DELETE", ""); } }
public static async Task DoRequest(BaseEvent @event, int port) { var url = string.Format("http://localhost:{0}/API/Message/NewMessage", port); var message = _serializer.Serialize<BaseEvent>(@event); using (WebClient client = new WebClient()) { client.Encoding = Encoding.UTF8; client.Headers["Content-Type"] = "application/json; charset=utf-8"; await client.UploadStringTaskAsync(new Uri(url), "POST", message); } }
public static async Task<string> PostJson(string url, string jsonData) { using(var wc = new WebClient()) { wc.Encoding = Encoding.UTF8; wc.Headers.Add(HttpRequestHeader.ContentType, "application/json"); var response = await wc.UploadStringTaskAsync(new Uri(url), jsonData); return response; } }
internal static async Task<string> DownloadDataAsync(string method, string baseUrl, string data, string contentType, string authHeader) { var client = new WebClient(); if (!String.IsNullOrEmpty(contentType)) client.Headers["Content-Type"] = contentType; if (!String.IsNullOrEmpty(authHeader)) client.Headers["Authorization"] = authHeader; if (method == "POST") { return await client.UploadStringTaskAsync(new Uri(baseUrl), data); } return await client.DownloadStringTaskAsync(new Uri(baseUrl)); }
//POST /api/automate HTTP/1.1 //Host: automatewebui.azurewebsites.net //Cache-Control: no-cache //Content-Type: application/x-www-form-urlencoded // //EmailAddress=jm_aba%40ahoo.com&Location=Lehliu&AgresivityRate=99 public async Task<string> Post(ClientStatistics clientStatistics) { try { var data = _encoder.Encode(clientStatistics); var client = new WebClient(); client.Headers[HttpRequestHeader.ContentType] = _encoder.ContentType; return await client.UploadStringTaskAsync(new Uri(_uri), "POST", data); } catch (Exception e) { return e.Message; } }
public static async Task<string> JsonRequest(string url, string data = null) { using(var wc = new WebClient()) { wc.Encoding = Encoding.UTF8; wc.Headers.Add(HttpRequestHeader.ContentType, "application/json"); var response = ""; if(string.IsNullOrWhiteSpace(data)) response = await wc.DownloadStringTaskAsync(new Uri(url)); else response = await wc.UploadStringTaskAsync(new Uri(url), data); return response; } }
public static async Task AlignTimeAsync() { long currentTime = Util.GetSystemUnixTime(); WebClient client = new WebClient(); try { string response = await client.UploadStringTaskAsync(new Uri(APIEndpoints.TWO_FACTOR_TIME_QUERY), "steamid=0"); TimeQuery query = JsonConvert.DeserializeObject<TimeQuery>(response); TimeAligner._timeDifference = (int)(query.Response.ServerTime - currentTime); TimeAligner._aligned = true; } catch (WebException) { return; } }
// Run an asynchronous command to the receiver. public async Task<string> RunCommandAsync(YamahaDevice device, string request) { using (var client = new WebClient()) { try { string url = "http://" + device.Address + CONTROL_URI; return await client.UploadStringTaskAsync(url, "POST", request); } catch (Exception e) { Log.Warning("Request failed with error: " + e.Message); } return default(string); } }
async public Task<JsonValue> SendAsync(string Path, string Method, string Data = "", Tuple<string, string>[] RequestHeaders = null) { var WebClient = new WebClient(); WebClient.Proxy = null; if (RequestHeaders != null) { foreach (var Header in RequestHeaders) WebClient.Headers.Add(Header.Item1, Header.Item2); } if (Method == "GET" || Method == "HEAD") { return JsonObject.Parse(await WebClient.DownloadStringTaskAsync(Client.Base + "/" + Path)); } else { return JsonObject.Parse(await WebClient.UploadStringTaskAsync(Client.Base + "/" + Path, Method, Data)); } }
private async void GenerateToken_Click(object sender, EventArgs e) { using (var webClient = new WebClient()) { Uri uri; try { uri = new Uri(_url + "auth/github"); } catch (Exception ex) { _log.Error(ex); MessageBox.Show("Invalid url: " + _url); return; } webClient.Headers.Add("Accept", "application/vnd.travis-ci.2+json"); webClient.Headers.Add("Content-Type", "application/json"); try { _loading.Visible = true; var data = "{\"github_token\":\"" + _githubToken.Text + "\"}"; var result = await webClient.UploadStringTaskAsync(uri, "POST", data); _loading.Visible = false; var deserializeObject = JsonConvert.DeserializeAnonymousType(result, new {access_token = ""}); TravisApiAccessToken = deserializeObject.access_token; Close(); } catch (WebException ex) { MessageBox.Show("Unable to connect: " + ex.Message); } catch (Exception ex) { _log.Error(ex); } finally { _loading.Visible = false; } } }
public static void SendEvent(List<Beacon> beacons) { var orderedBeaconsInSight = beacons.Where (b => (b.Proximity != CLProximity.Unknown)).OrderBy (b => b.Accuracy).ToList<Beacon> (); if (orderedBeaconsInSight.Count < 3) return; // 3 required for trilat String deviceId = UIDevice.CurrentDevice.IdentifierForVendor.AsString (); String json = "{\"deviceId\":\""+deviceId+"\",\"beaconsInSight\" : ["; for (int f=0; f<=2; f++){ json += "{\"id\":\"" + orderedBeaconsInSight [f].FriendlyName + "\",\"range\":" + orderedBeaconsInSight [f].Accuracy + "}"; json += (f == 2 ? "" : ","); } json += "]}"; using (WebClient client = new WebClient ()) { client.Headers.Add ("Content-Type", "application/json"); client.UploadStringTaskAsync ("http://" + IP_ADDRESS + ":9000/api/events", json); } }
public async Task<string> CallServerAsync(string path, ServerPostData postData) { await EnsureInitializedAsync(); string url = $"{BASE_URL}:{BasePort}/{path.ToLowerInvariant()}"; string json = JsonConvert.SerializeObject(postData); try { using (WebClient client = new WebClient()) { return await client.UploadStringTaskAsync(url, json); } } catch (WebException ex) { Telemetry.TrackException(ex); Down(); return string.Empty; } }
public static async Task<DrawingImage> Retrieve(DcrGraph graph) { var body = "src=" + graph.ExportToXml(); var tempFilePath = Path.Combine(Path.GetTempPath(), "SaveFile.svg"); using (WebClient wc = new WebClient()) { wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; //var encodedBody = SharpVectors.HttpUtility.UrlEncode(body); //if (encodedBody == null) //{ // return null; //} var encodedBody = Regex.Replace(body, @"[^\w\s<>/""=]", ""); //var encodedBody = body.Replace(" & ", "and"); // TODO: Replace all illegal characters...? if (encodedBody.Contains("_")) encodedBody = encodedBody.Replace("_", ""); var result = await wc.UploadStringTaskAsync("http://dcr.itu.dk:8023/trace/dcr", encodedBody); //TODO: don't save it as a file System.IO.File.WriteAllText(tempFilePath, result); } //conversion options WpfDrawingSettings settings = new WpfDrawingSettings(); settings.IncludeRuntime = true; settings.TextAsGeometry = true; FileSvgReader converter = new FileSvgReader(settings); var xamlFile = converter.Read(tempFilePath); return new DrawingImage(xamlFile); }
private async void Save_Click(object sender, RoutedEventArgs e) { var json = JsonConvert.SerializeObject(viewModel); WebClient webClient = new WebClient(); webClient.Headers["Content-Type"] = "application/json"; try { Save.IsEnabled = false; await webClient.UploadStringTaskAsync(new Uri("http://hopapiservice.azurewebsites.net/api/Hop", UriKind.Absolute), "POST", json); } catch (Exception) { MessageBox.Show("An error occured while trying to submit."); } finally { Save.IsEnabled = true; } MessageBox.Show("Added Successfully."); NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative)); }
public XkcdModule() : base("/xkcd") { Post["/", runAsync: true] = async (_, ct) => { var request = this.Bind<SlackRequest>(); if (request.Token != ConfigurationManager.AppSettings["SLACK_SLASH_COMMAND_TOKEN"]) return 403; if (request.Command != "/xkcd") return 400; string xkcdUrl; if (string.IsNullOrWhiteSpace(request.Text)) { xkcdUrl = await GetRandomComic(); } else { int result; xkcdUrl = int.TryParse(request.Text, out result) ? $"https://xkcd.com/{result}/" : await SearchGoogle(request.Text); } var data = new { text = xkcdUrl, channel = request.Channel_Name == "directmessage" ? "@" + request.User_Name : "#" + request.Channel_Name, unfurl_links = true }; using (var wc = new WebClient()) { await wc.UploadStringTaskAsync(ConfigurationManager.AppSettings["SLACK_WEBHOOK_URL"], JsonConvert.SerializeObject(data)); } return 200; }; }
public async Task <EsiModel> PostAsync(WebHeaderCollection headers, string address, string data, int cacheSeconds = 0) { System.Net.WebClient client = new System.Net.WebClient { Headers = headers, CachePolicy = new HttpRequestCachePolicy() }; client.Headers["UserAgent"] = _userAgent; CacheModel cachedItem = _cache.Get <CacheModel>(address); EsiModel esiModel = new EsiModel(); try { if (cacheSeconds == 0) { esiModel.Model = await client.UploadStringTaskAsync(address, data); esiModel = BuildHeaders(client.ResponseHeaders, esiModel); return(esiModel); } if (cachedItem != null) { if (DateTime.Compare(cachedItem.Expires, DateTime.UtcNow) <= 0) { esiModel.Model = cachedItem.Item; esiModel.Etag = cachedItem.Etag; esiModel.MaxPages = cachedItem.Page; return(esiModel); } if (!string.IsNullOrEmpty(cachedItem.Etag)) { client.Headers["If-None-Match"] = cachedItem.Etag; } string esiResponse = await client.UploadStringTaskAsync(address, data); esiModel = BuildHeaders(client.ResponseHeaders, esiModel); cachedItem = new CacheModel(esiResponse, esiModel.Etag, cacheSeconds, esiModel.MaxPages); _cache.Remove(address); _cache.Add(address, cachedItem); } else { string esiResponse = await client.UploadStringTaskAsync(address, data); esiModel = BuildHeaders(client.ResponseHeaders, esiModel); cachedItem = new CacheModel(esiResponse, esiModel.Etag, cacheSeconds, esiModel.MaxPages); _cache.Add(address, cachedItem); } esiModel.Model = cachedItem.Item; return(esiModel); } catch (WebException e) { EsiModel returned = BuildException(e, cachedItem, esiModel, address, data); if (returned != null) { return(returned); } throw; } }
public async void AuthenticateWithWNS() { IsRefreshInProgress = true; var urlEncodedSid = HttpUtility.UrlEncode(WNS_PACKAGE_SECURITY_IDENTIFIER); var urlEncodedSecret = HttpUtility.UrlEncode(WNS_SECRET_KEY); var body = String.Format(PayloadFormat, urlEncodedSid, urlEncodedSecret, AccessScope); string response = null; Exception exception = null; using (var client = new WebClient()) { client.Headers.Add("Content-Type", UrlEncoded); try { response = await client.UploadStringTaskAsync(new Uri(AccessTokenUrl), body); } catch (Exception e) { exception = e; Debug.WriteLine(String.Format("Failed WNS authentication. Error: {0}",e.Message)); } } if (exception == null && response != null) { oAuthToken = GetOAuthTokenFromJson(response); ScheduleTokenRefreshing(); } IsRefreshInProgress = false; OnAuthenticated?.Invoke(); }
public static Task<string> Post(string url, string data, string authToken) { var client = new WebClient { Encoding = Encoding.UTF8 }; client.Headers.Add("Content-Type:application/x-www-form-urlencoded"); client.Headers.Add(authToken != null ? AuthHeader(authToken) : "Host:www.box.net"); return client.UploadStringTaskAsync(new Uri(url), "POST", data); }
private async Task<string> RequestRawDataToServerAsync(string date) { string rawResult = null; using (var client = new WebClient()) { client.Headers.Add("Origin", "http://www.forexfactory.com"); client.Headers.Add("Referer", "http://www.forexfactory.com/index.php"); client.Headers.Add("X-Requested-With", "XMLHttpRequest"); client.Headers.Add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); client.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11"); client.Headers.Add("Cookie", string.Format( "__gads=ID=4cb0429a709ae2b1:T=1352673378:S=ALNI_MakhgWOmj0BAHVj_fEPqXcQvJsoAA; fftimezoneoffset=7; dstonoff=0; ffdstonoff=0; fftimezoneoffset=7; ffstartofweek=1; fftimeformat=0; ffverifytimes=1; notice_ffBlog=1357014276; flexHeight_flexBox_flex_minicalendar_=155; ffflextime_flex_minicalendar_=1357838496-0; ffcalendar=93bdedb64d9706a2bebaacef9cdeeb68da7c848ca-2-%7Bs-7-.calyear._i-0_s-8-.calmonth._i-0_%7D; __utma=113005075.2089994478.1352727369.1357842901.1357862156.185; __utmc=113005075; __utmz=113005075.1357455362.160.9.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); ffflex=a%3A1%3A%7Bs%3A16%3A%22Calendar_mainCal%22%3Ba%3A3%3A%7Bs%3A9%3A%22begindate%22%3Bs%3A16%3A%22{0}%22%3Bs%3A7%3A%22enddate%22%3Bs%3A16%3A%22{0}%22%3Bs%3A7%3A%22impacts%22%3Ba%3A1%3A%7Bs%3A4%3A%22high%22%3Bs%3A4%3A%22high%22%3B%7D%7D%7D; ffsessionhash=4e2aacfe2d66b5076c016bf88139ea81; flexHeight_flexBox_flex_calendar_mainCal=227; ffflextime_flex_calendar_mainCal=1357869548-0; fflastvisit=1352673368; fflastactivity=0", TodayDate)); rawResult = await client.UploadStringTaskAsync("http://www.forexfactory.com/flex.php?", string.Format( "s=&securitytoken=guest&do=saveoptions&setdefault=no&ignoreinput=no&flex%5BCalendar_mainCal%5D%5BidSuffix%5D=&flex%5BCalendar_mainCal%5D%5B_flexForm_%5D=flexForm&flex%5BCalendar_mainCal%5D%5BmodelData%5D=YTo3OntzOjEyOiJob21lQ2FsZW5kYXIiO2I6MTtzOjEyOiJ2aWV3aW5nVG9kYXkiO2I6MDtzOjExOiJwcmV2Q2FsTGluayI7czoxNDoiZGF5PWphbjEwLjIwMTMiO3M6MTE6Im5leHRDYWxMaW5rIjtzOjE0OiJkYXk9amFuMTIuMjAxMyI7czo3OiJwcmV2QWx0IjtzOjE3OiJZZXN0ZXJkYXk6IEphbiAxMCI7czo3OiJuZXh0QWx0IjtzOjE2OiJUb21vcnJvdzogSmFuIDEyIjtzOjk6InJpZ2h0TGluayI7YjoxO30%3D&flex%5BCalendar_mainCal%5D%5Bbegindate%5D={0}&flex%5BCalendar_mainCal%5D%5Benddate%5D={0}&flex%5BCalendar_mainCal%5D%5Bimpacts%5D%5Bhigh%5D=high&flex%5BCalendar_mainCal%5D%5B_cbarray_%5D=1&flex%5BCalendar_mainCal%5D%5Bcurrencies%5D%5Baud%5D=aud&flex%5BCalendar_mainCal%5D%5Bcurrencies%5D%5Bcad%5D=cad&flex%5BCalendar_mainCal%5D%5Bcurrencies%5D%5Bchf%5D=chf&flex%5BCalendar_mainCal%5D%5Bcurrencies%5D%5Bcny%5D=cny&flex%5BCalendar_mainCal%5D%5Bcurrencies%5D%5Beur%5D=eur&flex%5BCalendar_mainCal%5D%5Bcurrencies%5D%5Bgbp%5D=gbp&flex%5BCalendar_mainCal%5D%5Bcurrencies%5D%5Bjpy%5D=jpy&flex%5BCalendar_mainCal%5D%5Bcurrencies%5D%5Bnzd%5D=nzd&flex%5BCalendar_mainCal%5D%5Bcurrencies%5D%5Busd%5D=usd&flex%5BCalendar_mainCal%5D%5B_cbarray_%5D=1&flex%5BCalendar_mainCal%5D%5Beventtypes%5D%5Bgrowth%5D=growth&flex%5BCalendar_mainCal%5D%5Beventtypes%5D%5Binflation%5D=inflation&flex%5BCalendar_mainCal%5D%5Beventtypes%5D%5Bemployment%5D=employment&flex%5BCalendar_mainCal%5D%5Beventtypes%5D%5Bcentralbank%5D=centralbank&flex%5BCalendar_mainCal%5D%5Beventtypes%5D%5Bbonds%5D=bonds&flex%5BCalendar_mainCal%5D%5Beventtypes%5D%5Bhousing%5D=housing&flex%5BCalendar_mainCal%5D%5Beventtypes%5D%5Bsentiment%5D=sentiment&flex%5BCalendar_mainCal%5D%5Beventtypes%5D%5Bpmi%5D=pmi&flex%5BCalendar_mainCal%5D%5Beventtypes%5D%5Bspeeches%5D=speeches&flex%5BCalendar_mainCal%5D%5Beventtypes%5D%5Bmisc%5D=misc&flex%5BCalendar_mainCal%5D%5B_cbarray_%5D=1&false", date)).ConfigureAwait(false); } return rawResult; }
private async Task<Link[]> ParseTextToLinks(string text, bool deep) { Uri uri; List<Link> links = new List<Link>(); string pattern = @"(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.\-=]*)*\/?"; if (String.IsNullOrWhiteSpace(text) == false) { foreach (Match match in Regex.Matches(text, pattern)) { if (Uri.TryCreate(match.Value, UriKind.Absolute, out uri) == true) { if (uri.Authority == "nitroflare.com" || uri.Authority == "www.nitroflare.com") { if (uri.Segments.Length >= 3) { if (uri.Segments[1].TrimEnd('/').ToLower() == "view") { links.Add(new Link { Hosting = "nitroflare.com", Url = new Uri(match.Value.ToLower(), UriKind.Absolute) }); } else if (uri.Segments[1].TrimEnd('/').ToLower() == "folder") { using (WebClient client = new WebClient()) { try { client.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); string post = String.Format("userId={0}&folder={1}&page=1&perPage=50", uri.Segments[2].Trim('/'), Uri.EscapeDataString(uri.Segments[3].Trim('/'))); string data = await client.UploadStringTaskAsync("http://nitroflare.com/ajax/folder.php", post); string absolute = data.Replace(@"view\/", @"http://nitroflare.com/view/").Replace(@"\/", "/"); Link[] found = await this.ParseTextToLinks(absolute, false); links.AddRange(found); } catch (WebException) { // ignore } } } } } else if (deep == true) { using (WebClient client = new WebClient()) { try { string data = await client.DownloadStringTaskAsync(uri); Link[] found = await this.ParseTextToLinks(data, false); links.AddRange(found); } catch (WebException) { // ignore } } } } } } return links.ToArray(); }
/* /// <summary> /// Posts the data async. /// </summary> /// <returns>The data async.</returns> /// <param name="SerializedPostData">Serialized post data.</param> /// <param name="RestUrl">Rest URL.</param> /// <param name="APIName">Method name.</param> public async Task<string> PostDataAsync (string SerializedPostData, string RestUrl, string MethodName = "") { //var serializedContent = new StringContent (SerializeContent (json), Encoding.UTF8, "application/json"); var uri = new Uri (string.Format (RestUrl, MethodName)); HttpResponseMessage responsepost = null; responsepost = await client.PostAsync (uri, SerializedPostData); var contentpost = await responsepost.Content.ReadAsStringAsync (); if (responsepost.IsSuccessStatusCode) { return contentpost; } return string.Empty; }*/ /// <summary> /// Posts the data async. /// </summary> /// <returns>The data async.</returns> /// <param name="SerializedPostData">Serialized Post Data</param> /// <param name="RestUrl">Rest URL.</param> /// <param name="APIName">Method name.</param> public async Task<string> PostDataAsync (string SerializedPostData, string RestUrl, string APIName) { string result = string.Empty; try { WebClient webclient = new WebClient(); var uri = new Uri (string.Format (RestUrl, APIName)); webclient.Headers [HttpRequestHeader.ContentType] = "application/json"; result = await webclient.UploadStringTaskAsync (uri, SerializedPostData); return result; } catch (System.Exception sysExc) { Console.WriteLine ("Exception: {0}", sysExc); //throw; } return result; }