public static HttpClientHandler CreateHttpClientHandler() { var handler = new HttpClientHandler(); handler.ApplyProxy(); return handler; }
private void Initalize() { // Limit to maximum of 256 Connections ServicePointManager.DefaultConnectionLimit = 256; //Trust all certificates ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true); // TODO: Add Proxy Support Handler = new HttpClientHandler { AllowAutoRedirect = true, UseCookies = true, CookieContainer = new CookieContainer(), UseDefaultCredentials = false, Proxy = null, UseProxy = false }; // Create the HTTP Client Client = new HttpClient(Handler); Client.DefaultRequestHeaders.Clear(); Client.DefaultRequestHeaders.CacheControl = new CacheControlHeaderValue { MaxAge = TimeSpan.FromSeconds(0) }; Client.DefaultRequestHeaders.Accept.ParseAdd("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"); Client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36"); }
public async static Task<bool> Ping(ConnectionItem connectionItem) { JObject requestObject = new JObject( new JProperty("jsonrpc", "2.0"), new JProperty("id", 234), new JProperty("method", "JSONRPC.ping")); string requestData = requestObject.ToString(); HttpClientHandler handler = new HttpClientHandler(); HttpClient httpClient = new HttpClient(handler); string uriString = "http://" + connectionItem.IpAddress + ":" + connectionItem.Port.ToString() + "/jsonrpc?request="; httpClient.BaseAddress = new Uri(uriString); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, ""); request.Content = new StringContent(requestData); request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); //Required to be recognized as valid JSON request. HttpResponseMessage response = await httpClient.SendAsync(request); string responseString = await response.Content.ReadAsStringAsync(); if (responseString.Length == 0) return false; dynamic responseObject = JObject.Parse(responseString); bool isSuccessful = responseObject.result == "pong"; return isSuccessful; }
// <snippet508> public async Task<LogOnResult> LogOnAsync(string userId, string password) { using (var handler = new HttpClientHandler { CookieContainer = new CookieContainer() }) { using (var client = new HttpClient(handler)) { client.AddCurrentCultureHeader(); // Ask the server for a password challenge string var requestId = GenerateRequestId(); var response1 = await client.GetAsync(_clientBaseUrl + "GetPasswordChallenge?requestId=" + requestId); response1.EnsureSuccessStatusCode(); var challengeEncoded = await response1.Content.ReadAsAsync<string>(); var challengeBuffer = CryptographicBuffer.DecodeFromHexString(challengeEncoded); // Use HMAC_SHA512 hash to encode the challenge string using the password being authenticated as the key. var provider = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha512); var passwordBuffer = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8); var hmacKey = provider.CreateKey(passwordBuffer); var buffHmac = CryptographicEngine.Sign(hmacKey, challengeBuffer); var hmacString = CryptographicBuffer.EncodeToHexString(buffHmac); // Send the encoded challenge to the server for authentication (to avoid sending the password itself) var response = await client.GetAsync(_clientBaseUrl + userId + "?requestID=" + requestId +"&passwordHash=" + hmacString); // Raise exception if sign in failed response.EnsureSuccessStatusCode(); // On success, return sign in results from the server response packet var result = await response.Content.ReadAsAsync<UserInfo>(); var serverUri = new Uri(Constants.ServerAddress); return new LogOnResult { ServerCookieHeader = handler.CookieContainer.GetCookieHeader(serverUri), UserInfo = result }; } } }
public static HttpClientHandler CreateClientHandler(string serviceUrl, ICredentials credentials) { if (serviceUrl == null) { throw new ArgumentNullException("serviceUrl"); } // Set up our own HttpClientHandler and configure it HttpClientHandler clientHandler = new HttpClientHandler(); if (credentials != null) { // Set up credentials cache which will handle basic authentication CredentialCache credentialCache = new CredentialCache(); // Get base address without terminating slash string credentialAddress = new Uri(serviceUrl).GetLeftPart(UriPartial.Authority).TrimEnd(uriPathSeparator); // Add credentials to cache and associate with handler NetworkCredential networkCredentials = credentials.GetCredential(new Uri(credentialAddress), "Basic"); credentialCache.Add(new Uri(credentialAddress), "Basic", networkCredentials); clientHandler.Credentials = credentialCache; clientHandler.PreAuthenticate = true; } // Our handler is ready return clientHandler; }
public bool CancelAppointment(HackExchangeContext context, CalendarItem appointment) { var url = context.Endpoint; var request = new HttpRequestMessage(HttpMethod.Post, url); var postBodyTemplate = LoadXml("CancelAppointment"); var postBody = string.Format(postBodyTemplate, appointment.Id, appointment.ChangeKey); request.Content = new StringContent(postBody, Encoding.UTF8, "text/xml"); var clientHandler = new HttpClientHandler() { Credentials = context.Credentials }; using (var client = new HttpClient(clientHandler)) { var response = client.SendAsync(request).Result; var responseBody = response.Content.ReadAsStringAsync().Result; var doc = new XPathDocument(new StringReader(responseBody)); var nav = doc.CreateNavigator(); var nsManager = new XmlNamespaceManager(nav.NameTable); nsManager.AddNamespace("m", "http://schemas.microsoft.com/exchange/services/2006/messages"); nsManager.AddNamespace("t", "http://schemas.microsoft.com/exchange/services/2006/types"); var responseClass = EvaluateXPath(nav, nsManager, "//m:DeleteItemResponseMessage/@ResponseClass"); return responseClass == "Success"; } }
public void Ctor_ExpectedDefaultPropertyValues() { using (var handler = new HttpClientHandler()) { // Same as .NET Framework (Desktop). Assert.True(handler.AllowAutoRedirect); Assert.Equal(ClientCertificateOption.Manual, handler.ClientCertificateOptions); CookieContainer cookies = handler.CookieContainer; Assert.NotNull(cookies); Assert.Equal(0, cookies.Count); Assert.Null(handler.Credentials); Assert.Equal(50, handler.MaxAutomaticRedirections); Assert.False(handler.PreAuthenticate); Assert.Equal(null, handler.Proxy); Assert.True(handler.SupportsAutomaticDecompression); Assert.True(handler.SupportsProxy); Assert.True(handler.SupportsRedirectConfiguration); Assert.True(handler.UseCookies); Assert.False(handler.UseDefaultCredentials); Assert.True(handler.UseProxy); // Changes from .NET Framework (Desktop). Assert.Equal(DecompressionMethods.GZip | DecompressionMethods.Deflate, handler.AutomaticDecompression); Assert.Equal(0, handler.MaxRequestContentBufferSize); } }
public void Download(string url, System.IO.Stream stream) { try { using (var handler = new HttpClientHandler() { CookieContainer = _cookies }) using (var client = new HttpClient(handler) { BaseAddress = new Uri(_hostUrl) }) { client.DefaultRequestHeaders.Add("User-Agent", "WorkshareProtect"); if (_parameters.Count > 0) url += "?"; foreach (var kvp in _parameters) { url += kvp.Key + "=" + kvp.Value; url += "&"; } url = url.TrimEnd('&'); var response = client.GetAsync(url).Result; EnsureSuccessStatusCode(response); response.Content.ReadAsStreamAsync().Result.CopyTo(stream); } } catch (Exception e) { Logger.LogError(e); throw; } }
/// <summary> /// Post request /// </summary> /// <param name="uri">Enqueue endpoint URI</param> /// <param name="authenticationHeader">Authentication header</param> /// <param name="bodyStream">Body stream</param> /// <param name="message">ActivityMessage context</param> /// <returns></returns> public async Task<HttpResponseMessage> SendPostRequestAsync(Uri uri, Stream bodyStream, string externalCorrelationHeaderValue = null) { using (HttpClientHandler handler = new HttpClientHandler() { UseCookies = false }) { using (HttpClient httpClient = new HttpClient(handler)) { httpClient.DefaultRequestHeaders.Authorization = AuthenticationHelper.GetValidAuthenticationHeader(); // Add external correlation id header id specified and valid if (!string.IsNullOrEmpty(externalCorrelationHeaderValue)) { httpClient.DefaultRequestHeaders.Add(Program.ExternalCorrelationHeader, externalCorrelationHeaderValue); } if (bodyStream != null) { using (StreamContent content = new StreamContent(bodyStream)) { return await httpClient.PostAsync(uri, content); } } } } return new HttpResponseMessage() { Content = new StringContent("Request failed at client.", Encoding.ASCII), StatusCode = System.Net.HttpStatusCode.PreconditionFailed }; }
HttpAbfrage(String Ziel, HttpContent content) { //################################################################################################ var httpClient = new HttpClient(); // Neue httpClient instanz //################################################################################################## // mit Cockies aber nicht zu ende Programmiert weil wir keine Cockies nutzen CookieContainer cookie = new CookieContainer(); // Cockie Container Construcktor HttpClientHandler handler = new HttpClientHandler() // nutze beim zugriff cockies { }; HttpClient client = new HttpClient(handler as HttpMessageHandler) // neuer http client { BaseAddress = new Uri(GlobalData.Uri2 + Ziel + GlobalData.SessionID) // hier wird auch gleich die Session an das ziel angehangen // url aus uri 2 nutzen test2.php }; handler.UseCookies = false; // beim zugriff cockies nicht zulassen handler.UseDefaultCredentials = false; //################################################################################################# // Jetzt mit POST // Schritt 4 Abfrage abschicken und ergebnis entgegennehmen HttpResponseMessage response = await httpClient.PostAsync(client.BaseAddress, content); // schicke die abfrage an die Url , dann warte bis antwort komplett und speicher erst mal alles GlobalData.HttpResponse = await response.Content.ReadAsStringAsync(); // MessageDialog msgboxRespons = new MessageDialog(GlobalData.HttpResponse); // await msgboxRespons.ShowAsync(); // Zeige mir an was angekommen ist return GlobalData.HttpResponse; }
private static async Task<string> CallScrapperService() { HttpClientHandler handler = new HttpClientHandler(); handler.UseDefaultCredentials = true; HttpClient httpClient = new HttpClient(handler); httpClient.BaseAddress = new Uri("http://*****:*****@ AccessWebAsync().Result: " + AccessWebAsync().Result.Length); Console.WriteLine("await"); var urlContents = await getStringTask; Console.WriteLine("return"); return urlContents; }
public async Task<string> TryDownloadPackageFromFeed(string packageId, string version) { try { var handler = new HttpClientHandler(); handler.AllowAutoRedirect = false; using (var client = new HttpClient(handler)) { string requestUri = UrlHelper.V2FeedRootUrl + @"Package/" + packageId + @"/" + version; var response = await client.GetAsync(requestUri).ConfigureAwait(false); //print the header WriteLine("HTTP status code : {0}", response.StatusCode); WriteLine("HTTP header : {0}", response.Headers); if (response.StatusCode == HttpStatusCode.Found) { return response.Headers.GetValues("Location").FirstOrDefault(); } else { return null; } } } catch (HttpRequestException hre) { WriteLine("Exception : {0}", hre.Message); return null; } }
public Client(ISettings settings) { Settings = settings; Tuple<double, double> latLngFromFile = GetLatLngFromFile(); if (latLngFromFile != null && latLngFromFile.Item1 != 0 && latLngFromFile.Item2 != 0) { SetCoordinates(latLngFromFile.Item1, latLngFromFile.Item2, Settings.DefaultAltitude); } else { if (!File.Exists(lastcoords_file) || !File.ReadAllText(lastcoords_file).Contains(":")) Logger.Write("Missing \"\\Configs\\LastCoords.ini\", using default settings for coordinates and create a new one..."); SetCoordinates(Settings.DefaultLatitude, Settings.DefaultLongitude, Settings.DefaultAltitude); } //Setup HttpClient and create default headers var handler = new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate, AllowAutoRedirect = false }; _httpClient = new HttpClient(new RetryHandler(handler)); _httpClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Niantic App"); //"Dalvik/2.1.0 (Linux; U; Android 5.1.1; SM-G900F Build/LMY48G)"); _httpClient.DefaultRequestHeaders.ExpectContinue = false; _httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Connection", "keep-alive"); _httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "*/*"); _httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded"); }
public static async Task<bool> ChkVerifyCodeAnsyn(string verifyNo) { try { var handler = new HttpClientHandler() { CookieContainer = cookieContainers, AllowAutoRedirect = true, AutomaticDecompression = DecompressionMethods.GZip }; using (var httpClient = new HttpClient(handler)) { httpClient.DefaultRequestHeaders.Add("Host", "kyfw.12306.cn"); httpClient.DefaultRequestHeaders.Add("Origin", ConstantKey.loginorigin); httpClient.DefaultRequestHeaders.Add("Referer", ConstantKey.loginRefer); httpClient.DefaultRequestHeaders.Add("UserAgent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131"); ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, errors) => true; // 构造POST参数 var data = new FormUrlEncodedContent(new Dictionary<string, string>() { {"randCode", verifyNo}, {"rand", "sjrand"} }); var response = await httpClient.PostAsync(ConstantKey.loginChkVcode, data); response.EnsureSuccessStatusCode(); string content = await response.Content.ReadAsStringAsync(); if (string.IsNullOrEmpty(content) || !content.Contains("Y") || !content.Contains("true")) return false; return true; } } catch (Exception ex) { return false; } }
/// <summary> /// Authenticates a user. /// </summary> /// <param name="userName">Name of the user.</param> /// <param name="password">The password.</param> /// <param name="regionKey">The region key.</param> /// <returns>The async <see cref="Task"/>.</returns> public static async Task<CaasAccountDetails> Authenticate(string userName, string password, string regionKey) { var config = (ComputeConfigurationSection)ConfigurationManager.GetSection("compute"); var credentials = new NetworkCredential(userName, password); var handler = new HttpClientHandler { Credentials = credentials }; using (var client = new HttpClient(handler)) { var region = config.Regions.Cast<RegionConfigurationElement>().FirstOrDefault(r => r.Key == regionKey); if (region == null) { throw new ArgumentException($"The region with key '{regionKey}' does not exist in the app.config file."); } var responseSteam = await client.GetStreamAsync(region.BaseUrl + AuthUrl); var xdoc = XDocument.Load(responseSteam); XNamespace ns5 = "http://oec.api.opsource.net/schemas/directory"; var orgId = xdoc.Root.Element(ns5 + "orgId").Value; return new CaasAccountDetails { Credentials = new NetworkCredential(userName, password), OrgId = orgId, BaseUrl = region.BaseUrl, Roles = xdoc.Root.Elements(ns5 + "roles").Elements(ns5 + "role").Elements(ns5 + "name").Select(e => e.Value).ToList() }; } }
public static async Task<bool> SubmitComment(string issueNumber, string commentString) { // https://developer.atlassian.com/jiradev/api-reference/jira-rest-apis/jira-rest-api-tutorials/jira-rest-api-example-add-comment // https://grantadesign.atlassian.net/rest/api/latest/project/10000 // https://grantadesign.atlassian.net/rest/api/latest/issue/MI-9111/editmeta/ var credentials = new NetworkCredential(Constants.UserName, Constants.Password); var handler = new HttpClientHandler {Credentials = credentials, PreAuthenticate = true}; using (var client = new HttpClient(handler)) { var authHeader = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", Constants.UserName, Constants.Password)))); client.DefaultRequestHeaders.Authorization = authHeader; client.BaseAddress = new Uri("https://grantadesign.atlassian.net/rest/api/latest/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var jiraComment = new JiraComment { Body = commentString }; var response = await client.PostAsJsonAsync("issue/" + issueNumber + "/comment", jiraComment); if (response.IsSuccessStatusCode) { return true; } return false; } }
public static async Task<Image> LoginInitAndGetloginVcode(bool IsFirst = false) { try { var handler = new HttpClientHandler() { CookieContainer = cookieContainers, AllowAutoRedirect = true, AutomaticDecompression = DecompressionMethods.GZip }; using (var httpClient = new HttpClient(handler)) { httpClient.DefaultRequestHeaders.Add("Host", "kyfw.12306.cn"); httpClient.DefaultRequestHeaders.Add("Origin", ConstantKey.loginorigin); httpClient.DefaultRequestHeaders.Add("Referer", ConstantKey.loginRefer); httpClient.DefaultRequestHeaders.Add("UserAgent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131"); ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, errors) => true; if (IsFirst) { //loginInit string loginInit = await httpClient.GetStringAsync(ConstantKey.loginInit); if (string.IsNullOrEmpty(loginInit) || !loginInit.Contains("登录")) return null; //loginJs var resp = await httpClient.GetAsync(ConstantKey.loginJs); if (!resp.IsSuccessStatusCode) return null; } //VerifyCode var verifyStream = await httpClient.GetStreamAsync(ConstantKey.loginVcode); if (verifyStream == null) return null; return Image.FromStream(verifyStream); } } catch (Exception ex) { return null; } }
private async void OnIdentityProviderTapped(object sender, TappedRoutedEventArgs e) { var identityProvider = (IdentityProvider)((FrameworkElement)e.OriginalSource).DataContext; var webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync( WebAuthenticationOptions.None, new Uri(identityProvider.LoginUrl), new Uri("http://authentication.brainthud.com/api/federationcallback/end")); var start = webAuthenticationResult.ResponseData.LastIndexOf('=') + 1; var nameIdentifier = webAuthenticationResult.ResponseData.Substring(start, webAuthenticationResult.ResponseData.Length - start); var cookies = this.getCookies(nameIdentifier); var uri = new Uri(@"http://www.brainthud.com/api/Cards/"); var cookieContainer = new CookieContainer(); foreach(var cookie in cookies) { var cookieItem = new Cookie(cookie.Key, cookie.Value); cookieContainer.Add(uri, cookieItem); } var handler = new HttpClientHandler(); handler.CookieContainer =cookieContainer; var client = new HttpClient(handler); var response = client.GetAsync(uri).Result; var result = response.Content.ReadAsStringAsync().Result; var x = result; }
private async Task<JObject> AuthRequest(string path, string method, HttpContent data, RequestingUser u) { using(HttpClientHandler handler = new HttpClientHandler()) using(HttpClient client = new HttpClient(handler)) { HttpResponseMessage msg = null; string str; if(u != null) { handler.UseCookies = true; handler.CookieContainer = new CookieContainer(); u.Cookies.ToList().ForEach(c => handler.CookieContainer.Add(c)); client.DefaultRequestHeaders.Add("x-csrf", u.CsrfToken); } else { handler.UseCookies = false; } if(method.ToUpper() == WebRequestMethods.Http.Get.ToUpper()) { msg = await client.GetAsync(BungieNet.PlatformPath + path); } else if(method.ToUpper() == WebRequestMethods.Http.Post.ToUpper()) { msg = await client.PostAsync(BungieNet.PlatformPath + path, data); } str = await msg.Content.ReadAsStringAsync(); return JObject.Parse(str); } }
static void Main(string[] args) { //read config data from a command line parameters var user = args[0]; var password = args[1]; var database = args[2]; //base request builder for all requests containing user name and database name var handler = new HttpClientHandler { Credentials = new NetworkCredential(user, password) }; using (var client = CreateHttpClient(handler, user, database)) { var creationResponse = Create(client, new {name = "john", age = 15}); PrintResponse(creationResponse); var id = GetString("id", creationResponse); var readResponse = Read(client, id); PrintResponse(readResponse); var rev1 = GetString("_rev", readResponse); var updateResponse = Update(client, id, new {name = "john", age = 36, _rev = rev1}); PrintResponse(updateResponse); var rev2 = GetString("rev", updateResponse); // note that an update produces a "rev" in the response rather than "_rev" var deleteResponse = Delete(client, id, rev2); PrintResponse(deleteResponse); } }
private static HttpClient CreateHttpClient(HttpClientHandler handler, string user, string database) { return new HttpClient(handler) { BaseAddress = new Uri(string.Format("https://{0}.cloudant.com/{1}/", user, database)) }; }
public void SendSMS(Models.Message message) { var from = Settings.FromPhoneNumber; var phonePrefix = Settings.PhonePrefix; var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip, AllowAutoRedirect = false, UseCookies = true }; var httpclient = new HttpClient(handler); httpclient.BaseAddress = new Uri("https://www.ovh.com"); var request = "cgi-bin/sms/http2sms.cgi" .SetQueryParam("account", Settings.Account) .SetQueryParam("login", Settings.Nic) .SetQueryParam("password", Settings.Password) .SetQueryParam("from", from) .SetQueryParam("to", message.MobileNumber) .SetQueryParam("message", message.Content) .SetQueryParam("noStop", "1"); var response = httpclient.GetAsync(request); if (response.Result.StatusCode == HttpStatusCode.OK) { var content = response.Result.Content.ReadAsStringAsync().Result; } }
static void Main(string[] args) { var user = "******"; var password = "******"; var database = "database"; var handler = new HttpClientHandler { Credentials = new NetworkCredential(user, password) }; using (var client = CreateHttpClient(handler, user, database)) { string GetAllResponse = GetAll(client);//Query for all docs Console.Write(GetAllResponse); var creationResponse = Create(client, new {item = "carrot", check = false}); PrintResponse(creationResponse); var id = GetString("id", creationResponse);//Read a doc var readResponse = Read(client, id); PrintResponse(readResponse); var rev1 = GetString("_rev", readResponse);//Update var updateResponse = Update(client, id, new {item = "carrot", check = true, _rev = rev1}); PrintResponse(updateResponse); var rev2 = GetString("rev", updateResponse); //Delete var deleteResponse = Delete(client, id, rev2); PrintResponse(deleteResponse); Console.Read(); } }
public void DigestCredentials() { var requestUri = new Uri("http://localhost/DigestAuthDemo/"); var credCache = new CredentialCache { { new Uri("http://localhost/"), "Digest", new NetworkCredential("Test", "Test", "/") } }; using (var clientHander = new HttpClientHandler { Credentials = credCache, PreAuthenticate = true }) using (var httpClient = new HttpClient(clientHander)) { for (var i = 0; i < 5; i++) { var responseTask = httpClient.GetAsync(requestUri); responseTask.Result.EnsureSuccessStatusCode(); } } }
public static string Post(string url, PostBody postBody, int timeout = 5000) { try { Logger.Debug($"Post\t{url}"); using (var handler = new HttpClientHandler() { CookieContainer = new CookieContainer() }) using (var client = new HttpClient(handler)) { var content = new FormUrlEncodedContent(postBody.Body); var magicCodeName = string.Empty; if (Config.TryGet("MagicCodeType", out magicCodeName)) { var magicCodeValue = Config.TryGet("MagicCodeValue", ""); var magicCodePath = Config.TryGet("MagicCodePath", "/"); var magicCodeDomain = Config.TryGet("MagicCodeDomain", ".baidu.com"); handler.CookieContainer.Add(new Cookie(magicCodeName, magicCodeValue, magicCodePath, magicCodeDomain)); } var result = client.PostAsync(url, content).Result; result.EnsureSuccessStatusCode(); return result.Content.ReadAsStringAsync().Result; } } catch (Exception e) { Logger.Error(e.ToString()); return e.Message; } }
public NodeEngine() { _port = 1337; var sb = new StringBuilder(File.ReadAllText("server.js")); // add included scripts sb.AppendLine("var Handlebars = require('./Script/handlebars-1.0.0.js');"); foreach (var script in HandlebarsConfiguration.Instance.Include) { if (!string.IsNullOrEmpty(script.Name)) { sb.AppendLine("var " + script.Name + " = require('./" + script.Source + "');"); } else { sb.AppendLine("require('./" + script.Source + "');"); } } File.WriteAllText("hb-server.js", sb.ToString()); _server = new Process(); _server.StartInfo = GetStartInfo(); _server.Start(); HttpClientHandler handler = new HttpClientHandler(); handler.AllowAutoRedirect = true; handler.AutomaticDecompression = DecompressionMethods.None; _client = new HttpClient(handler); }
public IEnumerable<dynamic> GetCardsForSet(string setName) { // Undocumented feature to fix "The input stream contains too many delimiter characters" exception. // See http://forums.asp.net/post/4845421.aspx // Shouldn't be needed anymore once JSON.NET support is added to HttpClient post-beta. System.Net.Http.Formatting.MediaTypeFormatter.SkipStreamLimitChecks = true; var clientHandler = new HttpClientHandler { Credentials = new System.Net.NetworkCredential(ServiceUsername, ServicePassword) }; using(var client = new HttpClient(clientHandler)) { client.BaseAddress = new Uri(ServiceUrl); string setUrlPath = String.Format("sets/{0}", Uri.EscapeUriString(setName)); var response = client.GetAsync(setUrlPath).Result; response.EnsureSuccessStatusCode(); var set = response.Content.ReadAsAsync<System.Json.JsonObject>().Result; var cards = set["cards"].ReadAs<JsonArray>(); return cards; } }
/// <summary> /// You need to put this activity in a different agent that write the diagnostics log that you want to change. /// </summary> /// <param name="context"></param> protected override void Execute(CodeActivityContext context) { Thread.Sleep(30000); var findAndReplace = context.GetValue(FindAndReplaceStrings); _teamProjectUri = context.GetValue(TeamProjectUri); _buildUri = context.GetValue(BuildUri); var vssCredential = new VssCredentials(true); _fcClient = new FileContainerHttpClient(_teamProjectUri, vssCredential); var containers = _fcClient.QueryContainersAsync(new List<Uri>() { _buildUri }).Result; if (!containers.Any()) return; var agentLogs = GetAgentLogs(containers); if (agentLogs == null) return; using (var handler = new HttpClientHandler() { UseDefaultCredentials = true }) { var reader = DownloadAgentLog(agentLogs, handler); using (var ms = new MemoryStream()) { ReplaceStrings(findAndReplace, reader, ms); var response = UploadDocument(containers, agentLogs, ms); } } }
/// <summary> /// Executes the provided request asynchronously, returning the response object. /// </summary> /// <param name="request"><see cref="ISteamRequest"/> object for execution.</param> /// <returns><see cref="ISteamResponse"/> object containing the result of the request.</returns> public async Task<ISteamResponse> ExecuteAsync( ISteamRequest request ) { AuthenticateClient( this, request ); HttpRequestMessage httpRequest = BuildHttpRequest( request ); CookieContainer cookieContainer = new CookieContainer(); if( request.Cookies == null || request.Cookies.Count > 0 ) { foreach( Cookie cookie in request.Cookies ) cookieContainer.Add( httpRequest.RequestUri, cookie ); } HttpClientHandler httpHandler = new HttpClientHandler(); httpHandler.CookieContainer = cookieContainer; using( var httpClient = new HttpClient( httpHandler ) ){ httpClient.Timeout = TimeSpan.FromMilliseconds( ( ( request.Timeout > 0 ) ? request.Timeout : this.Timeout ) ); try { request.IncreaseNumAttempts(); return ConvertToResponse( request, await httpClient.SendAsync( httpRequest ), cookieContainer ); }catch( Exception ex ) { if( ex.InnerException != null && ex.InnerException is WebException ) return CreateErrorResponse( request, ex.InnerException ); return CreateErrorResponse( request, ex ); } } }
public System.Net.Http.HttpClient BuildPublicAppHttpClient() { var handler = new System.Net.Http.HttpClientHandler() { AutomaticDecompression = System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate }; return(new System.Net.Http.HttpClient(handler) { BaseAddress = new Uri(PublicWebHostUrl), }); }
public Analyze() { InitializeComponent(); var handler = new System.Net.Http.HttpClientHandler { }; p = new System.Net.Http.HttpClient(handler); updateNodeList(false); }
/// <summary> /// Initializes a new instance of the AutoRestLongRunningOperationTestService class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestLongRunningOperationTestService(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); }
/// <summary> /// Initializes a new instance of the AutoRestSwaggerBATFormDataService class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AutoRestSwaggerBATFormDataService(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); }
/// <summary> /// Initializes a new instance of the PolymorphicAnimalStore class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public PolymorphicAnimalStore(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); }
/// <summary> /// Initializes a new instance of the SequenceRequestResponseTest class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public SequenceRequestResponseTest(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); }
public IHttpClientHandler Create() { var handler = new Http.HttpClientHandler(); return(new HttpClientHandler(handler)); }
/// <summary> /// Initializes a new instance of the AutoRestLongRunningOperationTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestLongRunningOperationTestService(System.Uri baseUri, ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } }
/// <summary> /// Initializes a new instance of the AutoRestParameterizedCustomHostTestClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AutoRestParameterizedCustomHostTestClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); }
/// <summary> /// Initializes a new instance of the SwaggerDateTimeOffsetClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public SwaggerDateTimeOffsetClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); }
/// <summary> /// Initializes a new instance of the AutoRestReportService class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AutoRestReportService(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); }
/// <summary> /// Initializes a new instance of the CompositeBoolInt class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public CompositeBoolInt(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); }
/// <summary> /// Initializes a new instance of the MicrosoftAzureTestUrlClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected MicrosoftAzureTestUrlClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); }
/// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected StorageManagementClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); }
/// <summary> /// Initializes a new instance of the AutoRestReportServiceForAzureClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestReportServiceForAzureClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); }
/// <summary> /// Initializes a new instance of the AutoRestReportServiceForAzureClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestReportServiceForAzureClient(ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } }
/// <summary> /// Initializes a new instance of the AzureCompositeModelClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AzureCompositeModelClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); }
/// <summary> /// Initializes a new instance of the AutoRestParameterGroupingTestService class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestParameterGroupingTestService(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); }
/// <summary> /// Initializes a new instance of the AutoRestValidationTest class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AutoRestValidationTest(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); }
/// <summary> /// Initializes a new instance of the InternalClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> internal InternalClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); }
/// <summary> /// Initializes a new instance of the AutoRestUrlMutliCollectionFormatTestService class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AutoRestUrlMutliCollectionFormatTestService(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); }
protected override void ExecuteCmdlet() { if (Url.StartsWith("/")) { // prefix the url with the current web url Url = UrlUtility.Combine(ClientContext.Url, Url); } var accessToken = this.ClientContext.GetAccessToken(); var method = new HttpMethod(Method.ToString()); //var method = new HttpMethod(Method.ToString().ToUpper()); using (var handler = new System.Net.Http.HttpClientHandler()) { // we're not in app-only or user + app context, so let's fall back to cookie based auth if (String.IsNullOrEmpty(accessToken)) { SetAuthenticationCookies(handler, ClientContext); } using (var httpClient = new PnPHttpProvider(handler)) { var requestUrl = Url; HttpRequestMessage request = new HttpRequestMessage(method, requestUrl); request.Headers.Add("accept", "application/json;odata=nometadata"); if (Method == HttpRequestMethod.Merge) { method = HttpMethod.Post; request.Headers.Add("X-HTTP-Method", "MERGE"); } if (!string.IsNullOrEmpty(accessToken)) { request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken); } else { if (ClientContext.Credentials is NetworkCredential networkCredential) { handler.Credentials = networkCredential; } } request.Headers.Add("X-RequestDigest", (ClientContext as ClientContext).GetRequestDigest().GetAwaiter().GetResult()); if (Method == HttpRequestMethod.Post) { if (string.IsNullOrEmpty(ContentType)) { ContentType = "application/json"; } var contentString = Content is string?Content.ToString() : JsonConvert.SerializeObject(Content, Formatting.None); request.Content = new StringContent(contentString, System.Text.Encoding.UTF8); request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(ContentType); } HttpResponseMessage response = httpClient.SendAsync(request, new System.Threading.CancellationToken()).Result; if (response.IsSuccessStatusCode) { // If value empty, URL is taken var responseString = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); if (responseString != null) { #if NETSTANDARD2_1 WriteObject(System.Text.Json.JsonSerializer.Deserialize <object>(responseString)); #else WriteObject(new JavaScriptSerializer().DeserializeObject(responseString)); #endif } } else { // Something went wrong... throw new Exception(response.Content.ReadAsStringAsync().GetAwaiter().GetResult()); } } } }
/// <summary> /// Initializes a new instance of the RecursiveTypesAPI class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public RecursiveTypesAPI(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); }
public HttpClientHandler(Http.HttpClientHandler handler) { this.handler = handler; }
private bool unJoin(string comId, CookieContainer cc, MainForm form, config.config cfg) { for (int i = 0; i < 3; i++) { // var myPageUrl = "http://www.nicovideo.jp/my"; var comUrl = "https://www.nicovideo.jp/user/" + comId; var url = "https://www.nicovideo.jp/api/watchitem/delete"; var headers = new WebHeaderCollection(); // headers.Add("Upgrade-Insecure-Requests", "1"); headers.Add("User-Agent", util.userAgent); /* * try { * var cg = new CookieGetter(cfg); * var cgret = cg.getHtml5RecordCookie(url, isSub); * cgret.Wait(); * * if (cgret == null || cgret.Result == null) { * System.Threading.Thread.Sleep(3000); * continue; * } * var _cc = cgret.Result[0]; * * } catch (Exception e) { * return false; * } */ try { var pageRes = util.getPageSource(comUrl, cc); var token = util.getRegGroup(pageRes, "data-csrf-token=\"(.+?)\""); if (token == null) { token = util.getRegGroup(pageRes, "Globals.hash = '(.+?)'"); } if (token == null) { util.debugWriteLine("user unfollow token null " + comId); return(false); } var handler = new System.Net.Http.HttpClientHandler(); handler.UseCookies = true; handler.CookieContainer = cc; handler.Proxy = null; var http = new System.Net.Http.HttpClient(handler); http.DefaultRequestHeaders.Referrer = new Uri(url); /* * var content = new System.Net.Http.FormUrlEncodedContent(new Dictionary<string, string> * { * {"commit", "はい、フォローを解除します"}, {"time", time}, {"commit_key", commit_key} * }); */ var enc = Encoding.GetEncoding("UTF-8"); string data = "id_list[1][]=" + comId + "&token=" + token; byte[] postDataBytes = Encoding.ASCII.GetBytes(data); util.debugWriteLine("access__ followUser unjoin"); var req = (HttpWebRequest)WebRequest.Create(url); req.Method = "POST"; req.Proxy = null; req.CookieContainer = cc; req.Referer = url; req.ContentLength = postDataBytes.Length; req.ContentType = "application/x-www-form-urlencoded"; req.Headers.Add("X-Requested-With", "XMLHttpRequest"); req.Headers.Add("Accept-Encoding", "gzip,deflate"); req.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; using (var stream = req.GetRequestStream()) { try { stream.Write(postDataBytes, 0, postDataBytes.Length); } catch (Exception e) { util.debugWriteLine(e.Message + " " + e.StackTrace + " " + e.Source + " " + e.TargetSite); } } var res = req.GetResponse(); using (var getResStream = res.GetResponseStream()) using (var resStream = new System.IO.StreamReader(getResStream)) { var resStr = resStream.ReadToEnd(); var isSuccess = resStr.IndexOf("{\"delete_count\":1,\"status\":\"ok\"}") > -1; if (!isSuccess) { util.debugWriteLine(resStr); Thread.Sleep(3000); continue; } return(isSuccess); } } catch (Exception e) { //form.addLogText("フォロー解除に失敗しました。"); util.debugWriteLine(e.Message + e.StackTrace); continue; } } //form.addLogText("フォロー解除に失敗しました。"); util.debugWriteLine("フォロー解除失敗 " + comId); return(false); }
private bool join(string comId, CookieContainer cc, MainForm form, config.config cfg) { util.debugWriteLine("follow user " + comId); for (int i = 0; i < 3; i++) { var comUrl = "https://www.nicovideo.jp/user/" + comId; var url = "https://www.nicovideo.jp/api/watchitem/add"; var headers = new WebHeaderCollection(); // headers.Add("Upgrade-Insecure-Requests", "1"); headers.Add("User-Agent", util.userAgent); try { /* * var cg = new CookieGetter(cfg); * var cgret = cg.getHtml5RecordCookie(url, isSub); * cgret.Wait(); * * * // cgret.ConfigureAwait(false); * if (cgret == null || cgret.Result == null) { * System.Threading.Thread.Sleep(3000); * continue; * } * var _cc = cgret.Result[0]; * * // var _cc = cgret.Result[(isSub) ? 1 : 0]; * // util.debugWriteLine(cg.pageSource); * * var isJidouShounin = util.getPageSource(url, ref headers, cc, comUrl).IndexOf("自動承認されます") > -1; * // var _compage = util.getPageSource(url, ref headers, cc); * // var gateurl = "http://live.nicovideo.jp/gate/lv313793991"; * // var __gatePage = util.getPageSource(gateurl, ref headers, cc); * // var _compage2 = util.getPageSource(url, ref headers, cc); * // util.debugWriteLine(cc.GetCookieHeader(new Uri(url))); * var msg = (isJidouShounin ? "フォローを試みます。" : "自動承認ではありませんでした。") + util.getMainSubStr(isSub, true); * form.addLogText(msg); * * * if (!isJidouShounin) return false; */ } catch (Exception) { return(false); } try { var pageRes = util.getPageSource(comUrl, cc); if (pageRes == null) { continue; } var token = util.getRegGroup(pageRes, "data-csrf-token=\"(.+?)\""); if (token == null) { token = util.getRegGroup(pageRes, "Globals.hash = '(.+?)'"); } if (token == null) { util.debugWriteLine("user follow token null " + comId); return(false); } var handler = new System.Net.Http.HttpClientHandler(); handler.UseCookies = true; handler.CookieContainer = cc; handler.Proxy = null; var http = new System.Net.Http.HttpClient(handler); http.DefaultRequestHeaders.Referrer = new Uri(url); /* * var content = new System.Net.Http.FormUrlEncodedContent(new Dictionary<string, string> * { * {"mode", "commit"}, {"title", "フォローリクエスト"} * }); */ var enc = Encoding.GetEncoding("UTF-8"); string data = "item_type=1&item_id=" + comId + "&token=" + token; util.debugWriteLine(data); byte[] postDataBytes = Encoding.ASCII.GetBytes(data); util.debugWriteLine("access__ followUser join"); var req = (HttpWebRequest)WebRequest.Create(url); req.Method = "POST"; req.Proxy = null; req.CookieContainer = cc; req.Referer = url; req.ContentLength = postDataBytes.Length; req.ContentType = "application/x-www-form-urlencoded"; req.Headers.Add("X-Requested-With", "XMLHttpRequest"); req.Headers.Add("Accept-Encoding", "gzip,deflate"); req.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; using (var stream = req.GetRequestStream()) { try { stream.Write(postDataBytes, 0, postDataBytes.Length); } catch (Exception e) { util.debugWriteLine(e.Message + " " + e.StackTrace + " " + e.Source + " " + e.TargetSite); } } // stream.Close(); var res = req.GetResponse(); using (var getResStream = res.GetResponseStream()) using (var resStream = new System.IO.StreamReader(getResStream)) { var resStr = resStream.ReadToEnd(); var isSuccess = resStr.IndexOf("{\"status\":\"ok\"}") > -1; if (!isSuccess) { util.debugWriteLine(resStr); Thread.Sleep(3000); continue; } //var _m = (form.rec.isPlayOnlyMode) ? "視聴" : "録画"; //form.addLogText((isSuccess ? // "フォローしました。" + _m + "開始までしばらくお待ちください。" : "フォローに失敗しました。") + util.getMainSubStr(isSub, true)); return(isSuccess); } // resStream.Close(); // Task<HttpResponseMessage> _resTask = http.PostAsync(url, content); // _resTask.Wait(); // var _res = _resTask.Result; // var resTask = _res.Content.ReadAsStringAsync(); // resTask.Wait(); // var res = resTask.Result; // var a = _res.Headers; // if (res.IndexOf("login_status = 'login'") < 0) return null; // var cc = handler.CookieContainer; } catch (Exception e) { //form.addLogText("フォローに失敗しました。"); util.debugWriteLine(e.Message + e.StackTrace); continue; // return false; } } //form.addLogText("フォローに失敗しました。"); util.debugWriteLine("フォロー失敗"); return(false); }
private bool unJoin(string comId, CookieContainer cc, MainForm form, config.config cfg, bool isSub) { for (int i = 0; i < 5; i++) { // var myPageUrl = "http://www.nicovideo.jp/my"; // var comUrl = "https://com.nicovideo.jp/community/" + comId; var url = "https://com.nicovideo.jp/leave/" + comId; var headers = new WebHeaderCollection(); headers.Add("Upgrade-Insecure-Requests", "1"); headers.Add("User-Agent", util.userAgent); /* * try { * var cg = new CookieGetter(cfg); * var cgret = cg.getHtml5RecordCookie(url, isSub); * cgret.Wait(); * * if (cgret == null || cgret.Result == null) { * System.Threading.Thread.Sleep(3000); * continue; * } * var _cc = cgret.Result[0]; * * } catch (Exception e) { * return false; * } */ try { var leavePageRes = util.getPageSource(url, cc); var time = util.getRegGroup(leavePageRes, "\"hidden\" name=\"time\" value=\"(\\d+)\""); var commit_key = util.getRegGroup(leavePageRes, "\"hidden\" name=\"commit_key\" value=\"(.+?)\""); var handler = new System.Net.Http.HttpClientHandler(); handler.UseCookies = true; handler.CookieContainer = cc; handler.Proxy = null; var http = new System.Net.Http.HttpClient(handler); http.DefaultRequestHeaders.Referrer = new Uri(url); /* * var content = new System.Net.Http.FormUrlEncodedContent(new Dictionary<string, string> * { * {"commit", "はい、フォローを解除します"}, {"time", time}, {"commit_key", commit_key} * }); */ var enc = Encoding.GetEncoding("UTF-8"); string data = "time=" + time + "&commit_key=" + commit_key + "&commit=" + System.Web.HttpUtility.UrlEncode("はい、フォローを解除します", enc); byte[] postDataBytes = Encoding.ASCII.GetBytes(data); util.debugWriteLine("access__ followCommunity unjoin"); var req = (HttpWebRequest)WebRequest.Create(url); req.Method = "POST"; req.Proxy = null; req.CookieContainer = cc; req.Referer = url; req.ContentLength = postDataBytes.Length; req.ContentType = "application/x-www-form-urlencoded"; // req.Headers.Add("Referer", url); req.Headers.Add("Accept-Encoding", "gzip,deflate"); req.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; using (var stream = req.GetRequestStream()) { try { stream.Write(postDataBytes, 0, postDataBytes.Length); } catch (Exception e) { util.debugWriteLine(e.Message + " " + e.StackTrace + " " + e.Source + " " + e.TargetSite); } } var res = req.GetResponse(); using (var getResStream = res.GetResponseStream()) using (var resStream = new System.IO.StreamReader(getResStream)) { var resStr = resStream.ReadToEnd(); var isSuccess = resStr.IndexOf("このコミュニティのフォローを解除しました") > -1; return(isSuccess); } } catch (Exception e) { form.addLogText("フォロー解除に失敗しました。"); util.debugWriteLine(e.Message + e.StackTrace); continue; } } form.addLogText("フォロー解除に失敗しました。" + util.getMainSubStr(isSub, true)); util.debugWriteLine("フォロー解除失敗"); return(false); }
/// <summary> /// Initializes a new instance of the AutoRestParameterFlattening class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AutoRestParameterFlattening(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); }
/// <summary> /// Initializes a new instance of the StorSimple8000SeriesManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public StorSimple8000SeriesManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } }
/// <summary> /// Initializes a new instance of the AutoRestHttpInfrastructureTestService class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AutoRestHttpInfrastructureTestService(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); }
/// <summary> /// Sends a JSON OData request appending the SharePoint canary to the request header. /// Appending the canary to the request is necessary to perform write operations (e.g. create, update, delete list items) /// The canary is a security measure to prevent cross site scripting attacks /// </summary> /// <param name="uri">The request uri</param> /// <param name="method">The http method</param> /// <param name="requestContent">A stream containing the request content</param> /// <param name="clientHandler">The request client handler</param> /// <param name="authUtility">An instance of the auth helper to perform authenticated calls to SPO</param> /// <returns></returns> public static async Task<byte[]> SendODataJsonRequestWithCanary(Uri uri, HttpMethod method, Stream requestContent, HttpClientHandler clientHandler, SpoAuthUtility authUtility, bool _verbose) { verbose = _verbose; // Make a post request to {siteUri}/_api/contextinfo to get the canary var response = await HttpUtility.SendODataJsonRequest( new Uri(String.Format("{0}/_api/contextinfo", SpoAuthUtility.Current.SiteUrl)), HttpMethod.Post, null, clientHandler, SpoAuthUtility.Current); var serializer = new JavaScriptSerializer(); var deserializedResponse = serializer.Deserialize<Dictionary<string, object>>(Encoding.UTF8.GetString(response, 0, response.Length)); string canary = deserializedResponse["AuthURL"] as string; // Make the OData request passing the canary in the request headers return await HttpUtility.SendODataJsonRequest( uri, method, requestContent, clientHandler, SpoAuthUtility.Current, new Dictionary<string, string> { { "X-RequestDigest", canary } }); }