public GraphService(Activity activity) { AuthClientApp = PublicClientApplicationBuilder.Create(clientID) .WithRedirectUri($"msal{clientID}://auth") .Build(); var authProvider = new DelegateAuthenticationProvider(async(request) => { IEnumerable <IAccount> accounts = await AuthClientApp.GetAccountsAsync(); AuthenticationResult authResult; try { authResult = await AuthClientApp.AcquireTokenSilent(scopes, accounts.FirstOrDefault()) .ExecuteAsync(); } catch (MsalUiRequiredException) { authResult = await AuthClientApp.AcquireTokenInteractive(scopes) .WithParentActivityOrWindow(activity) .ExecuteAsync(); } request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authResult.AccessToken); }); // Use AndroidClientHandler as opposed to HttpClientHandler. var innerHandler = new AndroidClientHandler { AllowAutoRedirect = false }; var pipeline = GraphClientFactory.CreatePipeline(GraphClientFactory.CreateDefaultHandlers(authProvider), innerHandler); GraphClient = new GraphServiceClient(authProvider, new HttpProvider(pipeline, true, new Serializer())); }
static HttpMessageHandler CreateHttpMessageHandler() { // https://docs.microsoft.com/zh-cn/xamarin/android/app-fundamentals/http-stack?context=xamarin%2Fcross-platform&tabs=macos var handler = new AndroidClientHandler(); AddFiddlerRootCertificate(handler); return(handler); }
public static AndroidClientHandler CreateAndroidClientHandler() { // https://docs.microsoft.com/zh-cn/xamarin/android/app-fundamentals/http-stack?context=xamarin%2Fcross-platform&tabs=macos var handler = new AndroidClientHandler(); AddFiddlerRootCertificate(handler); GeneralHttpClientFactory.SetProxyToHandler(GeneralHttpClientFactory.DefaultProxy, handler); return(handler); }
public HttpService(Uri serverAddress) { this.serverAddress = serverAddress ?? throw new ArgumentNullException(nameof(serverAddress)); var androidClientHandler = new AndroidClientHandler(); httpClient = new HttpClient(androidClientHandler); }
protected override HttpClient CreateHttpClient() { var httpHandler = new AndroidClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }; return(new HttpClient(httpHandler, true)); }
public MainApplication(IntPtr handle, JniHandleOwnership transer) : base(handle, transer) { // NOTE: This is just here to stop the linker from removing AndroidClientHandler references var handler = new AndroidClientHandler(); if (!Resolver.IsSet) { SetIoc(this); } }
public HttpClient GetHttpClient() { var timeout = TimeSpan.FromSeconds(10); var handler = new AndroidClientHandler { ReadTimeout = timeout }; var client = new HttpClient(handler) { Timeout = timeout }; client.DefaultRequestHeaders.Add("Accept", "application/json"); return(client); }
async Task <string> RunNativeRequest() { string msg = string.Empty; try { var handler = new AndroidClientHandler { UseCookies = true, AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip, PreAuthenticate = true }; var httpClient = new HttpClient(handler); var responseMessage = await httpClient.GetAsync(serverUrl); msg = await((AndroidHttpResponseMessage)responseMessage).Content.ReadAsStringAsync(); } catch (Exception ex) { ShowMessage("Web exception occurred"); Console.WriteLine(ex.Message); } return(msg); }
public async Task <string> GetResultsDeflate(Uri url) { try { var clientHandler = new AndroidClientHandler { UseCookies = true }; clientHandler.ServerCertificateCustomValidationCallback += (sender, cert, chaun, ssl) => { return(true); }; using HttpClient hc = new HttpClient(clientHandler); HttpResponseMessage hr = await hc.GetAsync(url).ConfigureAwait(false); hr.EnsureSuccessStatusCode(); var encodeResults = await hr.Content.ReadAsStreamAsync().ConfigureAwait(false); DeflateStream deflateStream = new DeflateStream(encodeResults, CompressionMode.Decompress); StreamReader streamReader = new StreamReader(deflateStream, Encoding.UTF8); return(streamReader.ReadToEnd()); } catch (Exception ex) { Debug.WriteLine("GetResultsDeflate" + ex.Message); return(string.Empty); } }
/// <summary> /// 添加可信任证书,可用于调试时HTTPS抓包 /// </summary> /// <param name="handler"></param> /// <param name="certificateFileData">证书文件数据(文件流,内嵌资源流)</param> /// <param name="certificateFileType">证书文件类型,默认使用X.509</param> public static void AddTrustedCert( this AndroidClientHandler handler, Stream certificateFileData, string certificateFileType = "X.509") { var certificateFactory = CertificateFactory.GetInstance(certificateFileType); if (certificateFactory == null) { throw new NullReferenceException( $"CertificateFactory.GetInstance Fail, Type: {certificateFileType}"); } var certificate = certificateFactory.GenerateCertificate(certificateFileData); if (certificate == null) { throw new NullReferenceException("GenerateCertificate Fail"); } if (handler.TrustedCerts == null) { handler.TrustedCerts = new JavaList <Certificate>(); } handler.TrustedCerts.Add(certificate); }
static void AddFiddlerRootCertificate(AndroidClientHandler handler) { #if DEBUG //handler.AddTrustedCert(FiddlerRootCertificateStream); // 添加https抓包调试用的证书,仅测试环境下 #endif }
public HttpMessageHandler GetNativeHandler() { AndroidClientHandler handler = new AndroidClientHandler(); return(handler); }
public async Task UploadAsync(string path, string apiKey, string storageConnectionString, string viAccountName, Action <string> status) { var apiUrl = "https://api.videoindexer.ai"; var location = "westus2"; // create the http client var handler = new AndroidClientHandler(); var client = new HttpClient(handler); client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", apiKey); // obtain account information and access token var queryParams = CreateQueryString( new Dictionary <string, string> { { "generateAccessTokens", "true" }, { "allowEdit", "true" } }); var result = await client.GetAsync($"{apiUrl}/auth/{location}/Accounts?{queryParams}"); var json = await result.Content.ReadAsStringAsync(); var accounts = JsonConvert.DeserializeObject <AccountContractSlim[]>(json); // take the relevant account, here we simply take the first var accountInfo = accounts.First(a => a.Name.ToLower() == viAccountName); // we will use the access token from here on, no need for the apim key client.DefaultRequestHeaders.Remove("Ocp-Apim-Subscription-Key"); // upload a video var content = new MultipartFormDataContent(); var account = CloudStorageAccount.Parse(storageConnectionString); var blobClient = account.CreateCloudBlobClient(); var blobContainer = blobClient.GetContainerReference("uploads"); await blobContainer.CreateIfNotExistsAsync(); var destBlob = blobContainer.GetBlockBlobReference(Path.GetFileName(path)); await destBlob.DeleteIfExistsAsync(); double length; using (var stream = File.Open(path, FileMode.Open)) { length = Convert.ToDouble(stream.Length); } // Setup the number of the concurrent operations TransferManager.Configurations.ParallelOperations = 64; // Setup the transfer context and track the upoload progress var context = new SingleTransferContext(); context.ProgressHandler = new Progress <TransferStatus>((progress) => { status($"{Path.GetFileName(path)} {Math.Round(progress.BytesTransferred / length * 100d, 2)}% uploaded"); }); // Upload a local blob await TransferManager.UploadAsync(path, destBlob, null, context, CancellationToken.None); // get the video from URL var sharedAccessSignature = destBlob.GetSharedAccessSignature(new SharedAccessBlobPolicy { Permissions = SharedAccessBlobPermissions.Read, SharedAccessExpiryTime = DateTimeOffset.Now.AddHours(2d), SharedAccessStartTime = DateTimeOffset.Now.Subtract(TimeSpan.FromHours(2)) }); var videoUrl = destBlob.Uri.AbsoluteUri + sharedAccessSignature; queryParams = CreateQueryString( new Dictionary <string, string> { { "accessToken", accountInfo.AccessToken }, { "name", Path.GetFileName(path) }, { "description", "" }, { "privacy", "private" }, { "partition", "partition" }, { "videoUrl", videoUrl }, }); var uploadRequestResult = await client.PostAsync($"{apiUrl}/{accountInfo.Location}/Accounts/{accountInfo.Id}/Videos?{queryParams}", content); var uploadResult = await uploadRequestResult.Content.ReadAsStringAsync(); // get the video id from the upload result var videoId = ((JValue)JsonConvert.DeserializeObject <dynamic>(uploadResult)["id"]).Value.ToString(); status($"Video ID:{videoId}"); if (File.Exists(path)) { File.Delete(path); } // wait for the video index to finish while (true) { await Task.Delay(10000); queryParams = CreateQueryString( new Dictionary <string, string> { { "accessToken", accountInfo.AccessToken }, { "language", "English" }, }); var videoGetIndexRequestResult = await client.GetAsync($"{apiUrl}/{accountInfo.Location}/Accounts/{accountInfo.Id}/Videos/{videoId}/Index?{queryParams}"); var videoGetIndexResultContent = videoGetIndexRequestResult.Content; if (videoGetIndexResultContent == null) { continue; } var videoGetIndexResult = await videoGetIndexResultContent.ReadAsStringAsync(); var deserializeObject = JsonConvert.DeserializeObject <JObject>(videoGetIndexResult); var video = deserializeObject["videos"].First(); var processingState = ((JValue)video["state"]).Value.ToString(); var processingProgress = ((JValue)video["processingProgress"])?.Value.ToString(); var failureMessage = ((JValue)video["failureMessage"])?.Value.ToString(); var failureCode = ((JValue)video["failureCode"])?.Value.ToString(); if (string.IsNullOrWhiteSpace(failureMessage)) { status($"State:{processingState} {processingProgress}"); // job is finished if (processingState != "Uploaded" && processingState != "Processing") { //status($"Full JSON:{videoGetIndexResult}"); break; } } else { status($"State:{processingState} {failureCode}:{failureMessage}"); } } // search for the video queryParams = CreateQueryString( new Dictionary <string, string> { { "accessToken", accountInfo.AccessToken }, { "id", videoId }, }); var searchRequestResult = await client.GetAsync($"{apiUrl}/{accountInfo.Location}/Accounts/{accountInfo.Id}/Videos/Search?{queryParams}"); var searchResult = await searchRequestResult.Content.ReadAsStringAsync(); //status($"Search:{searchResult}"); // Generate video access token (used for get widget calls) client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", apiKey); var videoTokenRequestResult = await client.GetAsync($"{apiUrl}/auth/{accountInfo.Location}/Accounts/{accountInfo.Id}/Videos/{videoId}/AccessToken?allowEdit=true"); var videoAccessToken = (await videoTokenRequestResult.Content.ReadAsStringAsync()).Replace("\"", ""); client.DefaultRequestHeaders.Remove("Ocp-Apim-Subscription-Key"); // get insights widget url queryParams = CreateQueryString( new Dictionary <string, string> { { "accessToken", videoAccessToken }, { "widgetType", "Keywords" }, { "allowEdit", "true" }, }); var insightsWidgetRequestResult = await client.GetAsync($"{apiUrl}/{accountInfo.Location}/Accounts/{accountInfo.Id}/Videos/{videoId}/InsightsWidget?{queryParams}"); var insightsWidgetLink = insightsWidgetRequestResult.Headers.Location; //status($"Insights Widget url:{insightsWidgetLink}"); // get player widget url queryParams = CreateQueryString( new Dictionary <string, string> { { "accessToken", videoAccessToken }, }); var playerWidgetRequestResult = await client.GetAsync($"{apiUrl}/{accountInfo.Location}/Accounts/{accountInfo.Id}/Videos/{videoId}/PlayerWidget?{queryParams}"); var playerWidgetLink = playerWidgetRequestResult.Headers.Location; //status($"url:{playerWidgetLink}"); status("ready"); }
public object GetHttpHandler() { var handler = new AndroidClientHandler(); return(handler); }