public async System.Threading.Tasks.Task <PagingResultDto <T1> > CustomFormPostActionWithPagingResultAsync <T, T1>( string controller, string action, List <KeyValuePair <string, string> > parameters) where T : IDto where T1 : IDataModel <T>, new() { var requestMessage = new System.Net.Http.HttpRequestMessage { RequestUri = new Uri(GetFullUri(controller, action)), Method = System.Net.Http.HttpMethod.Post, }; requestMessage.Headers.Add("response", SerializeType.Protobuf); requestMessage.Headers.Add("token", _token); requestMessage.Content = new System.Net.Http.FormUrlEncodedContent(parameters); var handler = new System.Net.Http.HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }; var client = new System.Net.Http.HttpClient(handler); var response = await client.SendAsync(requestMessage); var responseBytes = await response.Content.ReadAsByteArrayAsync(); return(ProcessPagingResult <T, T1>(responseBytes)); }
// https://stackoverflow.com/questions/31150900/httprequestexception-when-trying-putasync System.Net.Http.HttpClient HttpApiClient() { System.Net.Http.HttpClientHandler clientHandler = new System.Net.Http.HttpClientHandler(); clientHandler.AllowAutoRedirect = false; return(new System.Net.Http.HttpClient(clientHandler)); }
private void heartBeater() { while (rm.rfu == rfu) { try { var url = "http://ow.live.nicovideo.jp/api/heartbeat"; var handler = new System.Net.Http.HttpClientHandler(); handler.UseCookies = true; handler.CookieContainer = container; var http = new System.Net.Http.HttpClient(handler); handler.UseProxy = true; handler.Proxy = util.httpProxy; http.Timeout = TimeSpan.FromSeconds(5); var contentStr = "{\"lang\":\"ja-jp\",\"locale\":\"JP\",\"seat_locale\":\"JP\",\"screen\":\"ScreenNormal\",\"v\":\"" + lvid + "\",\"datarate\":0}"; var content = new System.Net.Http.StringContent(contentStr); content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); var _res = http.PostAsync(url, content).Result; var res = _res.Content.ReadAsStringAsync(); } catch (Exception e) { util.debugWriteLine(e.Message + e.StackTrace + e.Source + e.TargetSite); } Thread.Sleep(60000); } }
private System.Net.Http.HttpClient CreateHTTPClient(string clientIPAddress) { System.Net.Http.HttpClient httpClient; if (remoteCertificateValidationCallback == null) { httpClient = new System.Net.Http.HttpClient(); } else { #if NET45 || NET46 || NET47 // special handling for .NET 4.5 & 4.6, since the HttpClientHandler does not have the ServerCertificateValidationCallback System.Net.Http.WebRequestHandler webRequestHandler = new System.Net.Http.WebRequestHandler(); webRequestHandler.ServerCertificateValidationCallback += remoteCertificateValidationCallback; httpClient = new System.Net.Http.HttpClient(webRequestHandler, true); #else System.Net.Http.HttpClientHandler httpClientHandler = new System.Net.Http.HttpClientHandler { ServerCertificateCustomValidationCallback = remoteCertificateValidationCallback.Invoke }; httpClient = new System.Net.Http.HttpClient(httpClientHandler, true); #endif } if (clientIPAddress != null) { httpClient.DefaultRequestHeaders.Add("X-Client-IP", clientIPAddress); } return(httpClient); }
public async Task <ViewResult> TFSProjects_01() { string url = "http://vchitfs:8080/tfs/DefaultCollection/_apis/projects?api-version=1.0"; SWAT.Client.WebClient.Models.TFSProjectResults table = null; System.Net.Http.HttpClientHandler handler = new System.Net.Http.HttpClientHandler() { UseDefaultCredentials = true }; using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(handler)) { client.BaseAddress = new Uri(url); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); System.Net.Http.HttpResponseMessage response = await client.GetAsync(url); if (response.IsSuccessStatusCode) { var data = await response.Content.ReadAsStringAsync(); table = Newtonsoft.Json.JsonConvert.DeserializeObject <SWAT.Client.WebClient.Models.TFSProjectResults>(data); using (System.IO.StringWriter sw = new System.IO.StringWriter()) { using (System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw)) { ViewBag.WorkItems = table; } } } } return(View(table)); }
// Prepare the OpenId Connect configuration manager, responsibile // for retrieving the JWT signing keys and cache them in memory. // See: https://openid.net/specs/openid-connect-discovery-1_0.html#rfc.section.4 private static IConfigurationManager <OpenIdConnectConfiguration> GetOpenIdConnectManager(AppConfig config) { // Avoid starting the real OpenId Connect manager if not needed, which would // start throwing errors when attempting to fetch certificates. if (!config.Global.AuthRequired) { return(new StaticConfigurationManager <OpenIdConnectConfiguration>( new OpenIdConnectConfiguration())); } var clientHandler = new System.Net.Http.HttpClientHandler(); clientHandler.ServerCertificateCustomValidationCallback = (a, b, c, d) => true; var client = new System.Net.Http.HttpClient(clientHandler); return(new ConfigurationManager <OpenIdConnectConfiguration>( config.Global.ClientAuth.Jwt.AuthIssuer + "/.well-known/openid-configuration", new OpenIdConnectConfigurationRetriever(), client) { // How often the list of keys in memory is refreshed. Default is 24 hours. AutomaticRefreshInterval = TimeSpan.FromHours(6), // The minimum time between retrievals, in the event that a retrieval // failed, or that a refresh is explicitly requested. Default is 30 seconds. RefreshInterval = TimeSpan.FromMinutes(1), }); }
/// <summary> /// /// </summary> /// <param name="ctx"></param> public override void HandleBefore(IContext ctx) { var _ctx = (Context)ctx; if (_ctx.Response != null) { return; } else if (string.IsNullOrEmpty(_ctx.RequestHost)) { _ctx.Response = new Error() { errmsg = "request host not set" }; return; } System.Net.Http.HttpClient httpclient; if (_ctx.Certificate == null) { httpclient = new System.Net.Http.HttpClient(); } else { var handler = new System.Net.Http.HttpClientHandler(); handler.ClientCertificateOptions = System.Net.Http.ClientCertificateOption.Manual; handler.SslProtocols = System.Security.Authentication.SslProtocols.Tls12; handler.ClientCertificates.Add(_ctx.Certificate); httpclient = new System.Net.Http.HttpClient(handler); } httpclient.BaseAddress = new Uri(_ctx.RequestHost); if (_ctx.Method == System.Net.Http.HttpMethod.Post) { System.Net.Http.HttpContent content; if (_ctx.HttpRequestBody != null) { content = new System.Net.Http.ByteArrayContent(_ctx.HttpRequestBody); } else if (!string.IsNullOrEmpty(_ctx.HttpRequestString)) { content = new System.Net.Http.StringContent(_ctx.HttpRequestString); } else { content = null; } if (content != null && _ctx.HttpRequestHeaders != null) { foreach (var item in _ctx.HttpRequestHeaders) { content.Headers.Add(item.Key, item.Value); } } _ctx.HttpTask = httpclient.PostAsync(_ctx.RequestPath, content); } else { _ctx.HttpTask = httpclient.GetAsync(_ctx.RequestPath); } }
/// <summary> /// Initializes a new instance of the PolymorphicAnimalStore class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </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 PolymorphicAnimalStore(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } this.BaseUri = baseUri; }
/// <summary> /// Initializes a new instance of the AutoRestUrlTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </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 AutoRestUrlTestService(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } this.BaseUri = baseUri; }
/// <summary> /// Initializes a new instance of the AzureCompositeModel class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </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="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AzureCompositeModel(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } this.BaseUri = baseUri; }
/// <summary> /// Initializes a new instance of the SwaggerSampleAPI class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </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 SwaggerSampleAPI(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } this.BaseUri = baseUri; }
/// <summary> /// Initializes a new instance of the AutoRestAzureSpecialParametersTestClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </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="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AutoRestAzureSpecialParametersTestClient(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } this.BaseUri = baseUri; }
public UnitTest1() { handler = new System.Net.Http.HttpClientHandler(); handler.CookieContainer = new CookieContainer(); client = new System.Net.Http.HttpClient(); client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2054.3 Safari/537.36"); }
/// <summary> /// Initializes a new instance of the ServerManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </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> protected ServerManagementClient(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } this.BaseUri = baseUri; }
/// <summary> /// Initializes a new instance of the BookFastBookingAPI class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </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> protected BookFastBookingAPI(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException(nameof(baseUri)); } this.BaseUri = baseUri; }
public HttpClientHandler(System.Net.Http.HttpClientHandler containedObject) { if ((containedObject == null)) { throw new System.ArgumentNullException("containedObject"); } this.containedObject = containedObject; }
/// <summary> /// Initializes a new instance of the SequenceRequestResponseTest class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </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 SequenceRequestResponseTest(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } this.BaseUri = baseUri; }
public static System.Net.Http.HttpClientHandler GetHttpClientHandler() { var handler = new System.Net.Http.HttpClientHandler() { AutomaticDecompression = System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate }; return(handler); }
private System.Net.Http.HttpClient CreateHttpClient() { var httpClientHandler = new System.Net.Http.HttpClientHandler { ServerCertificateCustomValidationCallback = configuration.SslTrustManager.ServerCertificateValidationCallback.Invoke }; return(new System.Net.Http.HttpClient(httpClientHandler, true)); }
public ScanServiceTest1() { handler = new System.Net.Http.HttpClientHandler(); handler.CookieContainer = new CookieContainer(); client = new System.Net.Http.HttpClient(); client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2054.3 Safari/537.36"); client.DefaultRequestHeaders.Add("Content-Type", "application/xml"); client.DefaultRequestHeaders.Add("Accept", "application/xml"); }
async private Task <string> watchingReservation(string token, string id, string mode) { util.debugWriteLine("watching reservation post " + token + " " + mode); try { var handler = new System.Net.Http.HttpClientHandler(); handler.UseCookies = true; handler.CookieContainer = cc; var http = new System.Net.Http.HttpClient(handler); handler.UseProxy = true; handler.Proxy = util.httpProxy; //var contentStr = "mode=auto_register&vid=" + id + "&token=" + token + "&_="; //util.debugWriteLine("reservation " + contentStr); var _content = new List <KeyValuePair <string, string> >(); if (mode == "watching_reservation_regist") { _content.Add(new KeyValuePair <string, string>("mode", "auto_register")); _content.Add(new KeyValuePair <string, string>("vid", id)); _content.Add(new KeyValuePair <string, string>("token", token)); _content.Add(new KeyValuePair <string, string>("_", "")); } else if (mode == "regist_finished") { _content.Add(new KeyValuePair <string, string>("accept", "true")); _content.Add(new KeyValuePair <string, string>("mode", "use")); _content.Add(new KeyValuePair <string, string>("vid", id)); _content.Add(new KeyValuePair <string, string>("token", token)); _content.Add(new KeyValuePair <string, string>("", "")); } //var content = new System.Net.Http.StringContent(contentStr); var content = new System.Net.Http.FormUrlEncodedContent(_content); //content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); http.Timeout = TimeSpan.FromSeconds(3); var url = "https://live.nicovideo.jp/api/watchingreservation"; var _t = http.PostAsync(url, content); _t.Wait(); var _res = _t.Result; var res = await _res.Content.ReadAsStringAsync(); // var a = _res.Headers; // if (res.IndexOf("login_status = 'login'") < 0) return null; // cc = handler.CookieContainer; return(res); // return cc; } catch (Exception e) { util.debugWriteLine("get watching exception " + e.Message + e.StackTrace); return(null); } }
void GenericHandlerSignature() { var httpHandler = new System.Net.Http.HttpClientHandler(); httpHandler.ServerCertificateCustomValidationCallback += InvalidValidation; var ShouldNotTrigger = new NonrelatedSignatureType(); ShouldNotTrigger.Callback += (sender, chain, certificate, SslPolicyErrors) => true; ShouldNotTrigger.Callback += (sender, chain, certificate, SslPolicyErrors) => false; }
/// <summary> /// Initializes a new instance of the SimpleAPIClient 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 SimpleAPIClient(Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } }
private async Task <IDictionary <string, object> > SendHttpRequest(TRootMessage rootMessage, bool isPollConnection) { ASSERT((rootMessage != null) && (rootMessage.Count > 0), "Missing parameter 'rootMessage'"); ASSERT(!string.IsNullOrWhiteSpace(HandlerUrl), "Property 'HandlerUrl' is supposed to be set here"); string strResponse; try { using (var handler = new System.Net.Http.HttpClientHandler() { CookieContainer = Cookies }) using (var client = new System.Net.Http.HttpClient(handler) { Timeout = System.Threading.Timeout.InfiniteTimeSpan }) { if (isPollConnection) { ASSERT(PollClient == null, "Property 'PollClient' is not supposed to be set here"); PollClient = client; var status = Status; switch (status) { case ConnectionStatus.Closing: case ConnectionStatus.Disconnected: throw new ArgumentException("Cannot create new connection while status is '" + status + "'"); } } var strMessage = rootMessage.ToJSON(); var content = new System.Net.Http.StringContent(strMessage, Encoding.UTF8, "application/json"); var response = await client.PostAsync(HandlerUrl, content); LOG("Receive response content"); strResponse = await response.Content.ReadAsStringAsync(); } } finally { if (isPollConnection) { ASSERT(PollClient != null, "Property 'PollClient' is supposed to be set here"); PollClient = null; } } var responseMessage = strResponse.FromJSONDictionary(); return(responseMessage); }
public HttpClient(string payloadContentType, string username, string password, Logger logger) { Logger = logger; PayloadContentType = payloadContentType; var httpHandler = new System.Net.Http.HttpClientHandler(); if (username != "" || password != "") { httpHandler.Credentials = new System.Net.NetworkCredential(username, password); } Client = new System.Net.Http.HttpClient(httpHandler); }
public PlatformClientStub(System.Net.CookieContainer cookie) { var handler = new System.Net.Http.HttpClientHandler() { CookieContainer = cookie }; PlusBaseUrl = new Uri("https://plus.google.com/u/0/"); TalkBaseUrl = new Uri("https://talkgadget.google.com/u/0/"); Cookies = cookie; NormalHttpClient = new System.Net.Http.HttpClient(handler); NormalHttpClient.DefaultRequestHeaders.Add( "user-agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.63 Safari/537.36"); StreamHttpClient = new System.Net.Http.HttpClient(handler); StreamHttpClient.Timeout = TimeSpan.FromMinutes(15); StreamHttpClient.DefaultRequestHeaders.Add( "user-agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.63 Safari/537.36"); }
} // End Sub Post public async System.Threading.Tasks.Task <int?> Get() { System.Collections.Generic.List <PersonModel> people = new System.Collections.Generic.List <PersonModel> { new PersonModel { FirstName = "Test", LastName = "One", Age = 25 }, new PersonModel { FirstName = "Test", LastName = "Two", Age = 45 } }; using (System.Net.Http.HttpClientHandler handler = new System.Net.Http.HttpClientHandler()) { handler.AutomaticDecompression = System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate; using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(handler, false)) { string json = Newtonsoft.Json.JsonConvert.SerializeObject(people); byte[] jsonBytes = System.Text.Encoding.UTF8.GetBytes(json); System.IO.MemoryStream ms = new System.IO.MemoryStream(); using (System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress, true)) { gzip.Write(jsonBytes, 0, jsonBytes.Length); } ms.Position = 0; System.Net.Http.StreamContent content = new System.Net.Http.StreamContent(ms); content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); content.Headers.ContentEncoding.Add("gzip"); System.Net.Http.HttpResponseMessage response = await client.PostAsync("http://localhost:54425/api/Gzipping", content); // System.Collections.Generic.IEnumerable<PersonModel> results = await response.Content.ReadAsAsync<System.Collections.Generic.IEnumerable<PersonModel>>(); string result = await response.Content.ReadAsStringAsync(); System.Collections.Generic.IEnumerable <PersonModel> results = Newtonsoft.Json.JsonConvert. DeserializeObject <System.Collections.Generic.IEnumerable <PersonModel> >(result); System.Diagnostics.Debug.WriteLine(string.Join(", ", results)); } } return(null); }
async public Task <string> getWatching() { util.debugWriteLine("watching post" + util.getMainSubStr(isSub, true)); try { var handler = new System.Net.Http.HttpClientHandler(); handler.UseCookies = true; handler.CookieContainer = container; var http = new System.Net.Http.HttpClient(handler); handler.UseProxy = false; http.DefaultRequestHeaders.Add("X-Frontend-Id", "91"); http.DefaultRequestHeaders.Add("X-Connection-Environment", "ethernet"); http.DefaultRequestHeaders.Add("Host", "api.cas.nicovideo.jp"); http.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0"); http.DefaultRequestHeaders.Add("Accept", "application/json"); // var contentStr = "{\"actionTrackId\":\"" + actionTrackId + "\",\"streamProtocol\":\"rtmp\",\"streamQuality\":\"" + requestQuality + "\""; var contentStr = "{\"actionTrackId\":\"" + actionTrackId + "\",\"streamProtocol\":\"https\",\"streamQuality\":\"" + requestQuality + "\""; if (streamCapacity != "ultrahigh") { contentStr += ", \"streamCapacity\":\"" + streamCapacity + "\""; } if (isLive) { contentStr += ",\"isBroadcaster\":" + isBroadcaster.ToString().ToLower() + ",\"isLowLatencyStream\":false"; } contentStr += "}"; util.debugWriteLine(contentStr + util.getMainSubStr(isSub, true)); var content = new System.Net.Http.StringContent(contentStr); content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); http.Timeout = TimeSpan.FromSeconds(5); var _t = http.PostAsync(watchingUrl, content); _t.Wait(); var _res = _t.Result; var res = await _res.Content.ReadAsStringAsync(); // var a = _res.Headers; // if (res.IndexOf("login_status = 'login'") < 0) return null; // cc = handler.CookieContainer; return(res); // return cc; } catch (Exception e) { util.debugWriteLine("get watching exception " + e.Message + e.StackTrace + util.getMainSubStr(isSub, true)); return(null); } }
async public Task <string> getWatchingPut() { util.debugWriteLine("watching put" + util.getMainSubStr(isSub, true)); for (var i = 0; i < 3; i++) { try { var handler = new System.Net.Http.HttpClientHandler(); handler.UseCookies = true; handler.CookieContainer = container; var http = new System.Net.Http.HttpClient(handler); handler.UseProxy = false; http.DefaultRequestHeaders.Add("X-Frontend-Id", "91"); http.DefaultRequestHeaders.Add("X-Connection-Environment", "ethernet"); http.DefaultRequestHeaders.Add("Host", "api.cas.nicovideo.jp"); http.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0"); http.DefaultRequestHeaders.Add("Accept", "application/json"); var contentStr = "{\"actionTrackId\":\"" + actionTrackId + "\",\"isBroadcaster\":\"" + isBroadcaster.ToString().ToLower() + "\"}"; http.Timeout = TimeSpan.FromSeconds(5); var content = new System.Net.Http.StringContent(contentStr); content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); //var _res = await http.PutAsync(watchingUrl, content); var t = http.PutAsync(watchingUrl, content); t.Wait(); var _res = t.Result; var res = await _res.Content.ReadAsStringAsync(); // var a = _res.Headers; // if (res.IndexOf("login_status = 'login'") < 0) return null; // cc = handler.CookieContainer; return(res); // return cc; } catch (Exception e) { util.debugWriteLine("watching put exception " + e.Message + e.StackTrace + e.Source + e.TargetSite + util.getMainSubStr(isSub, true)); // return null; } } return(null); }
internal static async Task <string> DownloadStringAsyncCookie(Int32 TimeOut, string UserAgent, string[][] RequestHeader, Uri DownloadUrl, string cookieString) { try { //Set the cookies to container System.Net.CookieContainer cookieContainer = new System.Net.CookieContainer(); foreach (string cookieSingle in cookieString.Split(',')) { Match cookieMatch = Regex.Match(cookieSingle, "(.+?)=(.+?);"); if (cookieMatch.Captures.Count > 0) { string CookieName = cookieMatch.Groups[1].ToString().Replace(" ", String.Empty); string CookieValue = cookieMatch.Groups[2].ToString().Replace(" ", String.Empty); cookieContainer.Add(DownloadUrl, new System.Net.Cookie(CookieName, CookieValue)); } } using (System.Net.Http.HttpClientHandler httpHandler = new System.Net.Http.HttpClientHandler()) { httpHandler.CookieContainer = cookieContainer; using (System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient(httpHandler)) { httpClient.Timeout = TimeSpan.FromMilliseconds(TimeOut); httpClient.DefaultRequestHeaders.Add("User-Agent", UserAgent); httpClient.DefaultRequestHeaders.Add("Cache-Control", "no-cache, no-store"); if (RequestHeader != null) { foreach (String[] StringArray in RequestHeader) { httpClient.DefaultRequestHeaders.Add(StringArray[0], StringArray[1]); } } string ConnectTask = await httpClient.GetStringAsync(DownloadUrl); Debug.WriteLine("DownloadStringAsyncCookie succeeded for url: " + DownloadUrl + " / " + ConnectTask.Length + "bytes"); return(ConnectTask); } } } catch (Exception ex) { Debug.WriteLine("DownloadStringAsyncCookie exception for url: " + DownloadUrl + " / " + ex.Message); return(String.Empty); } }
void GenericHandlerSignature() { var httpHandler = new System.Net.Http.HttpClientHandler(); //This is not RemoteCertificateValidationCallback delegate type, but Func<...> httpHandler.ServerCertificateCustomValidationCallback += InvalidValidation; //Noncompliant [flow9] //Generic signature check without RemoteCertificateValidationCallback var ShouldTrigger = new RelatedSignatureType(); ShouldTrigger.Callback += InvalidValidation; //Noncompliant [flow10] ShouldTrigger.Callback += CompliantValidation; var ShouldNotTrigger = new NonrelatedSignatureType(); ShouldNotTrigger.Callback += (sender, chain, certificate, SslPolicyErrors) => true; //Compliant, because signature types are not in expected order for validation ShouldNotTrigger.Callback += (sender, chain, certificate, SslPolicyErrors) => false; }
public PlatformClient(Uri plusBaseUrl, Uri talkBaseUrl, System.Net.CookieContainer cookie, IApiAccessor accessor, ICacheDictionary<string, ProfileCache, ProfileData> profileCacheStorage, CacheDictionary<string, ActivityCache, ActivityData> activityCacheStorage) { var handler = new System.Net.Http.HttpClientHandler() { CookieContainer = cookie }; Cookies = cookie; ServiceApi = accessor; PlusBaseUrl = plusBaseUrl; TalkBaseUrl = talkBaseUrl; NormalHttpClient = new System.Net.Http.HttpClient(handler); NormalHttpClient.DefaultRequestHeaders.Add("user-agent", ApiAccessorUtility.UserAgent); StreamHttpClient = new System.Net.Http.HttpClient(handler); StreamHttpClient.Timeout = TimeSpan.FromMinutes(15); StreamHttpClient.DefaultRequestHeaders.Add("user-agent", ApiAccessorUtility.UserAgent); People = new PeopleContainer(this, profileCacheStorage); Activity = new ActivityContainer(this, activityCacheStorage); Notification = new NotificationContainer(this); }