//calls the Bing Speech API Recognize method to perform speech recognition public static async Task <SpeechToText.SpeechRecognitionResult> RecognizeSpeechAync(byte[] bytes, bool maskProfanity = true) { SpeechToText.SpeechRecognitionResult result = null; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("Bearer", await GetAccessTokenAsync()); client.DefaultRequestHeaders.Accept.Add(new HttpMediaTypeWithQualityHeaderValue(@"application/json;text/xml")); var payload = new HttpBufferContent(bytes.AsBuffer()); payload.Headers.ContentType = new HttpMediaTypeHeaderValue(Common.AppConstants.RecognitionContentType); string language = "en-US"; string locale = "en-US"; string format = (maskProfanity) ? "detailed" : "simple"; string profanityFilter = (maskProfanity) ? "masked" : "raw"; string url = $"{Common.BingSpeechConstants.RecognitionBaseUrl}?language={language}&locale={locale}&format=detailed&profanity={profanityFilter}"; try { var response = await client.PostAsync(new Uri(url), payload); var content = await response.Content.ReadAsStringAsync(); result = JsonConvert.DeserializeObject <SpeechToText.SpeechRecognitionResult>(content); } catch (Exception ex) { } } return(result); }
public async static Task <Ocr.OcrAnalysisResult> GetOcrAnalysisAsync(Guid id, byte[] bytes) { HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", Common.CoreConstants.ComputerVisionApiSubscriptionKey); var payload = new HttpBufferContent(bytes.AsBuffer()); payload.Headers.ContentType = new HttpMediaTypeHeaderValue("application/octet-stream"); var results = await client.PostAsync(new Uri($"https://westus.api.cognitive.microsoft.com/vision/v1.0/ocr"), payload); Ocr.OcrAnalysisResult result = null; try { var analysisResults = await results.Content.ReadAsStringAsync(); var ocrAnalysisResult = JsonConvert.DeserializeObject <Ocr.OcrAnalysisResult>(analysisResults); result = ocrAnalysisResult; } catch (Exception ex) { } return(result); }
public async static Task <List <FaceDetectionResult> > DetectFacesAsync(byte[] bytes) { HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", Common.CoreConstants.FaceApiSubscriptionKey); var payload = new HttpBufferContent(bytes.AsBuffer()); payload.Headers.ContentType = new HttpMediaTypeHeaderValue("application/octet-stream"); string attributeFeatures = "age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise"; var response = await client.PostAsync(new Uri($"{CogsExplorer.Common.CoreConstants.CognitiveServicesBaseUrl}/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=false&returnFaceAttributes={attributeFeatures}"), payload); List <FaceDetectionResult> faceAnalysisResults = new List <FaceDetectionResult>(); try { var results = await response.Content.ReadAsStringAsync(); faceAnalysisResults = JsonConvert.DeserializeObject <List <FaceDetectionResult> >(results); } catch (Exception ex) { } return(faceAnalysisResults); }
private async Task <VideoOperationResult> InvokeEmotionAPIForVideo(IBuffer buffer, string queryString) { VideoOperationResult result = null; Uri uri = new Uri($"{RecognitionUrl[RecognitionType.Video]}?{queryString}"); HttpBufferContent content = new HttpBufferContent(buffer); content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/octet-stream"); var response = await httpClient.PostAsync(uri, content); if (response.StatusCode == HttpStatusCode.Accepted) { string location = string.Empty; response.Headers.TryGetValue("Operation-Location", out location); if (string.IsNullOrEmpty(location) == false) { Uri operationUri = new Uri(location); var locationResponse = await httpClient.GetAsync(operationUri); string jsonResult = await locationResponse.Content.ReadAsStringAsync(); result = JsonConvert.DeserializeObject <VideoOperationResult>(jsonResult); ProcessVideoResult(result); if (result.Status == VideoOperationStatus.Running) { var task = MonitorVideoProgress(operationUri); } } } return(result); }
public async static Task <List <Image.EmotionAnalysisResult> > GetEmotionAnalysisAsync(Guid id, byte[] bytes) { HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", Common.CoreConstants.EmotionApiSubscriptionKey); var payload = new HttpBufferContent(bytes.AsBuffer()); payload.Headers.ContentType = new HttpMediaTypeHeaderValue("application/octet-stream"); var results = await client.PostAsync(new Uri($"{CogsExplorer.Common.CoreConstants.CognitiveServicesBaseUrl}/emotion/v1.0/recognize"), payload); List <Image.EmotionAnalysisResult> emotionAnalysisResults = new List <Image.EmotionAnalysisResult>(); try { var analysisResults = await results.Content.ReadAsStringAsync(); emotionAnalysisResults = JsonConvert.DeserializeObject <List <Image.EmotionAnalysisResult> >(analysisResults); } catch (Exception ex) { } return(emotionAnalysisResults); }
/// <summary> /// Performs HTTP POST media byte array upload to Twitter. /// </summary> /// <param name="url">Url to upload to.</param> /// <param name="postData">Request parameters.</param> /// <param name="data">Image to upload.</param> /// <param name="name">Image parameter name.</param> /// <param name="fileName">Image file name.</param> /// <param name="contentType">Type of image: must be one of jpg, gif, or png.</param> /// <param name="reqProc">Request processor for handling results.</param> /// <returns>JSON response From Twitter.</returns> public async Task <string> PostImageAsync(string url, IDictionary <string, string> postData, byte[] data, string name, string fileName, string contentType, CancellationToken cancelToken) { WriteLog(url, nameof(PostImageAsync)); var multiPartContent = new HttpMultipartFormDataContent(); var byteArrayContent = new HttpBufferContent(data.AsBuffer()); byteArrayContent.Headers.Add("Content-Type", contentType); multiPartContent.Add(byteArrayContent, name, fileName); var cleanPostData = new Dictionary <string, string>(); foreach (var pair in postData) { if (pair.Value != null) { cleanPostData.Add(pair.Key, pair.Value); multiPartContent.Add(new HttpStringContent(pair.Value), pair.Key); } } var baseFilter = new HttpBaseProtocolFilter { AutomaticDecompression = Authorizer.SupportsCompression, ProxyCredential = Authorizer.ProxyCredential, UseProxy = Authorizer.UseProxy }; var handler = new PostMessageFilter(this, new Dictionary <string, string>(), url, baseFilter, cancelToken); var client = new HttpClient(handler); HttpResponseMessage msg = await client.PostAsync(new Uri(url), multiPartContent); return(await HandleResponseAsync(msg)); }
public async void Init() { image = new BitmapImage(); using (var stream = await file.OpenReadAsync()) { if (stream == null) { throw new Exception("画像のロードに失敗しました。"); } byte[] bytes = null; bytes = new byte[stream.Size]; using (DataReader reader = new DataReader(stream)) { await reader.LoadAsync((uint)stream.Size); reader.ReadBytes(bytes); } IBuffer buffer = null; using (DataWriter writer = new DataWriter()) { writer.WriteBytes(bytes); buffer = writer.DetachBuffer(); } httpContent = new HttpBufferContent(buffer); } using (var stream = await file.OpenReadAsync()) { image.SetSource(stream); } }
/// <summary> /// Send file to create asset (image or video) /// </summary> /// <param name="itemToSend">Byte array of the file</param> /// <param name="fileName">File's name</param> /// <param name="contentType">File's content type </param> /// <returns></returns> public async Task <string> PostFileAssetAsync(byte[] itemToSend, string fileName, string contentType) { string resultJson = string.Empty; string parameters = $"/api/{this.ApiVersion}file_asset"; try { HttpClient request = new HttpClient(); var content = new HttpMultipartFormDataContent(); HttpBufferContent itemContent = new HttpBufferContent(itemToSend.AsBuffer()); itemContent.Headers.ContentType = HttpMediaTypeHeaderValue.Parse(contentType); content.Add(itemContent, "file_upload", fileName); using (HttpResponseMessage response = await request.PostAsync(new Uri(this.HttpLink + parameters), content)) { resultJson = await response.Content.ReadAsStringAsync(); } if (!resultJson.Equals(string.Empty)) { return(JsonConvert.DeserializeObject <string>(resultJson)); } } catch (Exception ex) { throw new Exception($"[Device = {this.Name}; IP = {this.IpAddress}] Error while sending file.", ex); } return(null); }
/// <summary> /// Update order of active assets throught API /// </summary> /// <param name="newOrder"></param> /// <returns></returns> public async Task UpdateOrderAssetsAsync(string newOrder) { var postData = $"ids={newOrder}"; var data = System.Text.Encoding.UTF8.GetBytes(postData); string resultJson = string.Empty; string parameters = $"/api/{this.ApiVersion}assets/order"; try { HttpClient client = new HttpClient(); HttpBufferContent content = new HttpBufferContent(data.AsBuffer()); content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/x-www-form-urlencoded"); using (HttpResponseMessage response = await client.PostAsync(new Uri(this.HttpLink + parameters), content)) { resultJson = await response.Content.ReadAsStringAsync(); } } catch (WebException ex) { using (var stream = ex.Response.GetResponseStream()) using (var reader = new StreamReader(stream)) { throw new Exception(reader.ReadToEnd(), ex); } } catch (Exception ex) { throw new Exception($"[Device = {this.Name}; IP = {this.IpAddress}] Error while updating assets order.", ex); } }
public async static Task <ImageAnalysisResult> AnalyzeImageAsync(byte[] bytes) { HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", Common.CoreConstants.ComputerVisionApiSubscriptionKey); var payload = new HttpBufferContent(bytes.AsBuffer()); payload.Headers.ContentType = new HttpMediaTypeHeaderValue("application/octet-stream"); string visualFeatures = "Color,ImageType,Tags,Categories,Description,Adult"; var results = await client.PostAsync(new Uri($"{Common.CoreConstants.CognitiveServicesBaseUrl}/vision/v1.0/analyze?visualFeatures={visualFeatures}"), payload); ImageAnalysisResult result = null; try { var analysisResults = await results.Content.ReadAsStringAsync(); var imageAnalysisResult = JsonConvert.DeserializeObject <ImageAnalysisInfo>(analysisResults); result = new ImageAnalysisResult() { id = imageAnalysisResult.requestId, details = imageAnalysisResult, caption = imageAnalysisResult.description.captions.FirstOrDefault().text, tags = imageAnalysisResult.description.tags.ToList(), }; } catch (Exception ex) { } return(result); }
public async void LoginOut() { init(); thedata.DataToOut(); thedata.TransferDataToLoginOut(); string url = "http://w.dlut.edu.cn/cgi-bin/srun_portal"; //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); //request.Method = "POST"; //request.ContentType = "application/x-www-form-urlencoded"; Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); HttpBufferContent buffer = new HttpBufferContent(thedata.OutData.AsBuffer()); Windows.Web.Http.HttpResponseMessage response = await httpClient.PostAsync(new Uri(url), buffer).AsTask(cts.Token); Result = await response.Content.ReadAsStringAsync().AsTask(cts.Token); if (Result.IndexOf("成功") >= 0) { loginresponse = "注销成功"; } else if (Result.IndexOf("失败") >= 0) { loginresponse = "注销失败"; } else { loginresponse = "请检查网络"; } MessageDialog message = new MessageDialog(loginresponse); await message.ShowAsync(); }
protected override async Task <SearchResponse> SearchAsync(SearchRequest request) { var content = new HttpBufferContent(GBEncoding.GetBytes($"s={request.Keyword}").AsBuffer()) { Headers = { ContentType = new Windows.Web.Http.Headers.HttpMediaTypeHeaderValue("application/x-www-form-urlencoded") } }; var doc = await PostDoc(searchUri, content); var r = new SearchResponse(); var box = doc.GetElementbyId("sitembox"); if (box is null) { var bf = new BookDataBrief(); parseBookMeta(bf, doc); parseBookPage(bf, doc); r.Books.Add(bf); } else { foreach (var item in box.Elements("dl")) { var title = item.SelectSingleNode("./dd[1]/h3/a"); var key = title.GetAttributeValue("href", ""); key = idReg.Match(key).Groups[1].Value; var author = item.SelectSingleNode("./dd[2]/span[1]"); var status = item.SelectSingleNode("./dd[2]/span[2]"); var wordCount = item.SelectSingleNode("./dd[2]/span[4]"); var tags = item.SelectNodes("./dd[2]/a").EmptyIfNull(); var des = item.SelectSingleNode("./dd[3]"); var latestName = item.SelectSingleNode("./dd[4]/a"); var latestTime = item.SelectSingleNode("./dd[4]/span"); var image = item.SelectSingleNode("./dt[1]/a/img"); r.Books.Add(new BookDataBrief { Title = title.GetInnerText(), Author = author.GetInnerText(), Key = key, CoverUri = image?.GetAttribute("_src", BaseUri, null), Description = des.GetInnerText(), WordCount = int.Parse(wordCount.GetInnerText()), Tags = tags.Select(n => n.GetInnerText()).ToArray(), IsFinished = status.GetInnerText().Contains("完结"), LatestChapter = new ChapterDataBrief { UpdateTime = DateTime.Parse(latestTime.GetInnerText()), Key = latestName.GetAttribute("href", ""), Title = latestName.GetInnerText(), } }); } } return(r); }
/// <summary>Submits a POST request. Returns null on success, otherwise returns error information.</summary> /// <param name="baseUrl">Root URL for the API.</param> /// <param name="tableName">The table name to add to the end of the baseUrl.</param> /// <param name="data">The data payload to post.</param> /// <param name="cred">Authentication credentials if needed.</param> /// <param name="canceller">A object that can be sued to canel the request. </param> /// <returns>Null on success otherwise an error message.</returns> public static async Task <string> PostTable([NotNull] string baseUrl, [NotNull] string tableName, [NotNull] string data, [CanBeNull] Creds cred = null, [CanBeNull] CancellationToken?canceller = null) { if (!IsInternetAvailable()) { //Responses starting with "Error:" should be filtered as failures. return("Error: No Internet, post request aborted."); } // Must add the AllowUI=false setting otherwise it tries enumerating UI and doesn't report errors properly. var client = new HttpClient(new HttpBaseProtocolFilter { AllowUI = false }); var tokenHeader = "X-ZUMO-AUTH"; var headers = client.DefaultRequestHeaders; if (cred != null) { headers.Add(tokenHeader, cred.Token); } var url = UrlCombiner.CombineAsSeparateElements(baseUrl, tableName); if (canceller == null) { var cs = new CancellationTokenSource(TimeSpan.FromSeconds(DefaultTimeout)); canceller = cs.Token; } try { var buffUtf8 = CryptographicBuffer.ConvertStringToBinary(data, BinaryStringEncoding.Utf8); IHttpContent content = new HttpBufferContent(buffUtf8, 0, buffUtf8.Length); var body = await content.ReadAsStringAsync(); content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/json"); var response = await client.PostAsync(url, content).AsTask((CancellationToken)canceller); var it = response.Content; return(response.IsSuccessStatusCode ? null : $"Error: Request returned {response.StatusCode} ({response.ReasonPhrase}), Content:{it}"); } catch (TaskCanceledException) { Debug.WriteLine($"Req '{tableName}' cancelled ot timedout."); return("Error: Cancelled or timed out."); } catch (Exception ex) { Debug.WriteLine($"Req '{tableName}' error: {ex}"); return($"Error: NetFail: {ex.Message}, {ex.InnerException}, END"); } }
private async Task <byte[]> PostWebData(Uri uri, byte[] data) { HttpClient client = new HttpClient(); HttpBufferContent body = data != null ? new HttpBufferContent(WindowsRuntimeBufferExtensions.AsBuffer(data)) : (HttpBufferContent)null; HttpResponseMessage response = await client.PostAsync(uri, (IHttpContent)body); IBuffer ibuff = await response.get_Content().ReadAsBufferAsync(); byte[] buff = WindowsRuntimeBufferExtensions.ToArray(ibuff); return(buff); }
public static async Task <IAsyncOperationWithProgress <HttpResponseMessage, HttpProgress> > PostAsync(Uri uri, StorageFile file) { using (HttpClient client = new HttpClient()) { using (var content = new HttpBufferContent(await FileIOHelper.GetBuffer(file))) { var response = client.PostAsync(uri, content); return(response); } } }
private async void postData(byte[] TempData) { string url = "http://w.dlut.edu.cn/cgi-bin/srun_portal"; Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); HttpBufferContent buffer = new HttpBufferContent(TempData.AsBuffer()); Windows.Web.Http.HttpResponseMessage response = await httpClient.PostAsync(new Uri(url), buffer).AsTask(cts.Token); this.loginresponse = await response.Content.ReadAsStringAsync().AsTask(cts.Token); }
/// <summary> /// Initializes a new instance of the <see cref="ContentResult"/> class. /// </summary> /// <param name="buffer">The body content.</param> /// <param name="contentType">The content type header.</param> public ContentResult(IBuffer buffer, HttpMediaTypeHeaderValue contentType) { if (buffer.Length == 0) { throw new ArgumentOutOfRangeException("buffer"); } if (contentType == null) { throw new ArgumentException("contentType"); } Content = new HttpBufferContent(buffer); ContentType = contentType; }
public async Task <WeiboResult> ShareImageAsync(byte[] image, string text) { if (image == null) { throw new ArgumentNullException(nameof(image)); } if (text == null) { throw new ArgumentNullException(nameof(text)); } if (string.IsNullOrWhiteSpace(text)) { throw new ArgumentException("Text could not be empty", nameof(text)); } if (!UserInfo.CheckUseable()) { string authorizeCode = await this.GetAuthorizeCodeAsync(); await this.Authorize(authorizeCode); } Uri uri = new Uri("https://upload.api.weibo.com/2/statuses/upload.json"); HttpBufferContent bufferContent = new HttpBufferContent(image.AsBuffer()); HttpMultipartFormDataContent content = new HttpMultipartFormDataContent(); content.Add(new HttpStringContent(UserInfo.Token), "access_token"); content.Add(new HttpStringContent(text), "status"); content.Add(bufferContent, "pic", "pic.jpg"); using (HttpClient client = new HttpClient()) { HttpResponseMessage response; try { response = await client.PostAsync(uri, content); } catch (Exception ex) { throw new Exception("Network error", ex); } return(await response.Content.ReadAsJsonAsync <WeiboResult>()); } }
/// <summary> /// Update specific asset /// </summary> /// <param name="a">Asset to update</param> /// <returns>Asset updated</returns> public async Task <Asset> UpdateAssetAsync(Asset a) { Asset returnedAsset = new Asset(); JsonSerializerSettings settings = new JsonSerializerSettings(); IsoDateTimeConverter dateConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fff'Z'" }; settings.Converters.Add(dateConverter); string json = JsonConvert.SerializeObject(a, settings); var postData = $"model={json}"; var data = System.Text.Encoding.UTF8.GetBytes(postData); string resultJson = string.Empty; string parameters = $"/api/{this.ApiVersion}assets/{a.AssetId}"; try { HttpClient client = new HttpClient(); HttpBufferContent content = new HttpBufferContent(data.AsBuffer()); content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/x-www-form-urlencoded"); using (HttpResponseMessage response = await client.PutAsync(new Uri(this.HttpLink + parameters), content)) { resultJson = await response.Content.ReadAsStringAsync(); } if (!resultJson.Equals(string.Empty)) { returnedAsset = JsonConvert.DeserializeObject <Asset>(resultJson, settings); } } catch (WebException ex) { using (var stream = ex.Response.GetResponseStream()) using (var reader = new StreamReader(stream)) { throw new Exception(reader.ReadToEnd(), ex); } } catch (Exception ex) { throw new Exception($"[Device = {this.Name}; IP = {this.IpAddress}] Error while updating asset.", ex); } return(returnedAsset); }
private async Task <ImageAnalysisResult> GetImageAnalysisAsync(byte[] bytes) { ImageAnalysisResult result = null; try { using (var client = new HttpClient()) { client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", CoreConstants.ComputerVisionApiSubscriptionKey); var payload = new HttpBufferContent(bytes.AsBuffer()); payload.Headers.ContentType = new HttpMediaTypeHeaderValue("application/octet-stream"); var analysisFeatures = "Color,ImageType,Tags,Categories,Description,Adult,Faces"; var uri = new Uri($"{CoreConstants.CognitiveServicesBaseUrl}/analyze?visualFeatures={analysisFeatures}"); using (var results = await client.PostAsync(uri, payload)) { var analysisResults = await results.Content.ReadAsStringAsync(); var imageAnalysisResult = JsonConvert.DeserializeObject <ImageAnalysisInfo>(analysisResults); result = new ImageAnalysisResult { id = Guid.NewGuid().ToString(), details = imageAnalysisResult, caption = imageAnalysisResult.description.captions.FirstOrDefault()?.text, tags = imageAnalysisResult.description.tags.ToList() }; if (string.IsNullOrEmpty(result.caption)) { result.caption = "No caption"; } } } } catch (Exception ex) { Debug.WriteLine($"ComputerVisionService.GetImageAnalysisAsync Exception: {ex}"); } return(result); }
private async Task<List<EmotionData>> InvokeEmotionAPIForImage(IBuffer buffer, string contentType, string queryString) { Uri uri = new Uri($"{RecognitionUrl[RecognitionType.Image]}?{queryString}"); HttpBufferContent content = new HttpBufferContent(buffer); content.Headers.ContentType = new HttpMediaTypeHeaderValue(contentType); var response = await httpClient.PostAsync(uri, content); if (response.StatusCode == HttpStatusCode.Ok) { string jsonContent = await response.Content.ReadAsStringAsync(); var emotionResponse = JsonConvert.DeserializeObject<List<EmotionData>>(jsonContent); return emotionResponse; } else { return null; } }
internal static Task <AsyncResponse> HttpPostAsync(Uri url, string contentType, byte[] content, string authorizationHeader, ConnectionOptions options, CancellationToken cancellationToken, IProgress <UploadProgressInfo> progress = null) { if (options == null) { options = ConnectionOptions.Default; } var req = new HttpRequestMessage(HttpMethod.Post, url); #if WIN_RT var httpContent = new HttpBufferContent(content.AsBuffer()); httpContent.Headers.ContentType = HttpMediaTypeHeaderValue.Parse(contentType); #else var httpContent = new ByteArrayContent(content); httpContent.Headers.ContentType = MediaTypeHeaderValue.Parse(contentType); #endif req.Content = httpContent; return(ExecuteRequest(req, authorizationHeader, options, cancellationToken, progress)); }
public async static Task <Handwriting.Operations.HandwritingOperationResult> GetHandwritingAnalysisAsync(Guid id, byte[] bytes) { HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", Common.CoreConstants.ComputerVisionApiSubscriptionKey); var payload = new HttpBufferContent(bytes.AsBuffer()); payload.Headers.ContentType = new HttpMediaTypeHeaderValue("application/octet-stream"); var response = await client.PostAsync(new Uri($"https://westus.api.cognitive.microsoft.com/vision/v1.0/recognizeText"), payload); Handwriting.Operations.HandwritingOperationResult result = null; try { string operationLocation = response.Headers["Operation-Location"]; string status = ""; HttpResponseMessage results = null; Handwriting.Operations.HandwritingOperationResult handwritingAnalysisResult = null; while (status != "Succeeded") { await Task.Delay(1000); results = await client.GetAsync(new Uri(operationLocation)); var analysisResults = await results.Content.ReadAsStringAsync(); handwritingAnalysisResult = JsonConvert.DeserializeObject <Handwriting.Operations.HandwritingOperationResult>(analysisResults); status = handwritingAnalysisResult.status; } result = handwritingAnalysisResult; } catch (Exception ex) { } return(result); }
private async Task <List <EmotionData> > InvokeEmotionAPIForImage(IBuffer buffer, string contentType, string queryString) { Uri uri = new Uri($"{RecognitionUrl[RecognitionType.Image]}?{queryString}"); HttpBufferContent content = new HttpBufferContent(buffer); content.Headers.ContentType = new HttpMediaTypeHeaderValue(contentType); var response = await httpClient.PostAsync(uri, content); if (response.StatusCode == HttpStatusCode.Ok) { string jsonContent = await response.Content.ReadAsStringAsync(); var emotionResponse = JsonConvert.DeserializeObject <List <EmotionData> >(jsonContent); return(emotionResponse); } else { return(null); } }
/// <summary> /// HTTP Post request to specified Uri. /// </summary> /// <param name="requestUri">Uri to make OAuth request.</param> /// <param name="tokens">Tokens to pass in request.</param> /// <param name="boundary">Boundary used to separate data.</param> /// <param name="content">Data to post to server.</param> /// <returns>String result.</returns> public async Task <string> ExecutePostMultipartAsync(Uri requestUri, TwitterOAuthTokens tokens, string boundary, byte[] content) { JToken mediaId = null; try { using (var multipartFormDataContent = new HttpMultipartFormDataContent(boundary)) { using (var byteContent = new HttpBufferContent(content.AsBuffer())) { multipartFormDataContent.Add(byteContent, "media"); using (var request = new HttpHelperRequest(requestUri, HttpMethod.Post)) { var requestBuilder = new TwitterOAuthRequestBuilder(requestUri, tokens, "POST"); request.Headers.Authorization = HttpCredentialsHeaderValue.Parse(requestBuilder.AuthorizationHeader); request.Content = multipartFormDataContent; using (var response = await HttpHelper.Instance.SendRequestAsync(request).ConfigureAwait(false)) { string jsonResult = await response.GetTextResultAsync().ConfigureAwait(false); JObject jObj = JObject.Parse(jsonResult); mediaId = jObj["media_id_string"]; } } } } } catch (ObjectDisposedException) { // known issue // http://stackoverflow.com/questions/39109060/httpmultipartformdatacontent-dispose-throws-objectdisposedexception } return(mediaId.ToString()); }
async Task AppendChunksAsync(string url, ulong mediaID, byte[] data, string name, string fileName, string contentType, CancellationToken cancelToken) { const int ChunkSize = 500000; for ( int segmentIndex = 0, skip = 0; skip < data.Length; segmentIndex++, skip = segmentIndex * ChunkSize) { int take = Math.Min(data.Length - skip, ChunkSize); byte[] chunk = data.Skip(skip).Take(ChunkSize).ToArray(); var multiPartContent = new HttpMultipartFormDataContent(); var byteArrayContent = new HttpBufferContent(chunk.AsBuffer()); byteArrayContent.Headers.Add("Content-Type", contentType); multiPartContent.Add(byteArrayContent, name, fileName); multiPartContent.Add(new HttpStringContent("APPEND"), "command"); multiPartContent.Add(new HttpStringContent(mediaID.ToString()), "media_id"); multiPartContent.Add(new HttpStringContent(segmentIndex.ToString()), "segment_index"); var baseFilter = new HttpBaseProtocolFilter { AutomaticDecompression = Authorizer.SupportsCompression, ProxyCredential = Authorizer.ProxyCredential, UseProxy = Authorizer.UseProxy }; var filter = new PostMessageFilter(this, new Dictionary <string, string>(), url, baseFilter, CancellationToken); using (var client = new HttpClient(filter)) { HttpResponseMessage msg = await client.PostAsync(new Uri(url), multiPartContent); await HandleResponseAsync(msg); } } }
public async static Task <bool> AddPersonFaceAsync(string personGroupId, string personId, byte[] bytes, string fileName, Facerectangle faceRectangle) { bool successful = false; HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", Common.CoreConstants.FaceApiSubscriptionKey); var payload = new HttpBufferContent(bytes.AsBuffer()); payload.Headers.ContentType = new HttpMediaTypeHeaderValue("application/octet-stream"); try { var response = await client.PostAsync(new Uri($"{CogsExplorer.Common.CoreConstants.CognitiveServicesBaseUrl}/face/v1.0/persongroups/{personGroupId}/persons/{personId}/persistedFaces?userData={fileName}&targetFace={faceRectangle.left},{faceRectangle.top},{faceRectangle.width},{faceRectangle.height}"), payload); var results = await response.Content.ReadAsStringAsync(); } catch (Exception ex) { } return(successful); }
public async void PostByteArray(byte[] data) { var httpClient = new HttpClient(); var webService = WebServerUrl + "data"; var resourceUri = new Uri(WebServerUrl); try { IBuffer buffer = data.AsBuffer(); using (HttpBufferContent content = new HttpBufferContent(buffer)) { content.Headers.Add("Content-Type", "text/html; charset=utf-8"); content.Headers.ContentLength = buffer.Length; var response = await httpClient.PostAsync(resourceUri, content); Debug.WriteLine(response); } } catch (TaskCanceledException ex) { // Handle request being canceled due to timeout. } }
public async Task <string> PostFileAsync(string url, IDictionary <string, object> toPost, string filename, string fieldname, IBuffer buffer, CancellationTokenSource cts) { var result = string.Empty; try { using (var client = new HttpClient()) { string boundary = $"---------------------{DateTime.Now.Ticks.ToString("x")}"; var httpContent = new HttpMultipartFormDataContent(boundary); foreach (var item in toPost) { httpContent.Add(new HttpStringContent(item.Value.ToString(), Windows.Storage.Streams.UnicodeEncoding.Utf8), item.Key); } var imageContent = new HttpBufferContent(buffer); httpContent.Add(imageContent, fieldname, EncodeToIso(filename)); var response = await client.PostAsync(new Uri(url), httpContent).AsTask(cts.Token); var buf = await response.Content.ReadAsBufferAsync(); result = _gbk.GetString(buf.ToArray()); } } catch (Exception ex) { cts.Cancel(); cts.Dispose(); string err = $"请检查网络连接是否正常。\r\n{ex.Message}"; ShowError(err, "PostFileAsync 请求失败"); } return(result); }
public async Task <string> PostFileAsync(string url, IDictionary <string, object> toPost, string filename, string filetype, string fieldname, byte[] buffer) { var result = string.Empty; var cts = new CancellationTokenSource(); try { using (var client = new HttpClient()) { string boundary = "---------------------" + DateTime.Now.Ticks.ToString("x"); var httpContent = new HttpMultipartFormDataContent(boundary); foreach (var item in toPost) { httpContent.Add(new HttpStringContent(item.Value.ToString(), Windows.Storage.Streams.UnicodeEncoding.Utf8), item.Key); } var imageContent = new HttpBufferContent(WindowsRuntimeBufferExtensions.AsBuffer(buffer)); httpContent.Add(imageContent, fieldname, filename); var response = await client.PostAsync(new Uri(url), httpContent).AsTask(cts.Token); var buf = await response.Content.ReadAsBufferAsync(); byte[] bytes = WindowsRuntimeBufferExtensions.ToArray(buf, 0, (int)buf.Length); result = gbk.GetString(bytes, 0, bytes.Length); } } catch (Exception ex) { cts.Cancel(); await new MessageDialog(ex.Message + "\n\n请尝试刷新或检查网络连接是否正常!", "POSTFILE请求失败").ShowAsync(); } return(result); }
public static async Task<IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress>> PostAsync(Uri uri, StorageFile file) { using (HttpClient client = new HttpClient()) { using (var content = new HttpBufferContent(await FileIOHelper.GetBuffer(file))) { var response = client.PostAsync(uri, content); return response; } } }
public async Task SendData() { var client = new HttpClient(); var content = new HttpMultipartFormDataContent(); var imageContent = new HttpBufferContent(data.imageBuffer); content.Add(imageContent, "userpic", "userpic.bmp"); var name = new HttpStringContent(data.name); content.Add(name, "name"); var color = new HttpStringContent(data.color.color.ToString()); content.Add(color, "color"); var stick = new HttpStringContent(data.stickNum); content.Add(stick, "stick"); var gid = new HttpStringContent(data.gameId); content.Add(gid, "gid"); try { var res = await client.PostAsync(new Uri("http://mspjp-iot-test.azurewebsites.net/insertUser"), content); if (!res.IsSuccessStatusCode) { throw new Exception("Access failed." + res.ReasonPhrase); } } catch (Exception ex) { var message = new MessageDialog(ex.Message, "ふむ。最初からやり直しですな。"); await message.ShowAsync(); this.Frame.Navigate(typeof(InitPage01)); } }
/// <summary> /// 分享图片到微博 /// </summary> /// <param name="image">图片数据</param> /// <param name="text">图片描述</param> /// <returns>分享结果</returns> /// <exception cref="ArgumentNullException">image 为 null</exception> /// <exception cref="ArgumentNullException">text 为 null</exception> /// <exception cref="ArgumentException">text 为空字符串</exception> /// <exception cref="AuthorizeException">授权已过期,并且用户取消重新授权</exception> /// <exception cref="HttpException">网络异常</exception> /// <remarks>执行完成后请检查对象的 IsSuccess 属性,以获取是否成功</remarks> public async Task<Models.Weibo> ShareImageAsync(byte[] image, string text) { if (image == null) { throw new ArgumentNullException(nameof(image)); } if (text == null) { throw new ArgumentNullException(nameof(text)); } if (string.IsNullOrWhiteSpace(text)) { throw new ArgumentException("text could not be empty", nameof(text)); } if (LocalAccessToken.Useable == false) { string authorizeCode = await GetAuthorizeCodeAsync(); await Authorize(authorizeCode); } Uri uri = new Uri("https://upload.api.weibo.com/2/statuses/upload.json"); HttpBufferContent bufferContent = new HttpBufferContent(image.AsBuffer()); HttpMultipartFormDataContent content = new HttpMultipartFormDataContent(); content.Add(new HttpStringContent(LocalAccessToken.Token), "access_token"); content.Add(new HttpStringContent(text), "status"); content.Add(bufferContent, "pic", "pic.jpg"); using (HttpClient client = new HttpClient()) { HttpResponseMessage response; try { response = await client.PostAsync(uri, content); } catch (Exception ex) { throw new HttpException("network error", ex); } return await response.Content.ReadAsJsonAsync<Models.Weibo>(); } }
internal static Task<AsyncResponse> HttpPostAsync(Uri url, string contentType, byte[] content, string authorizationHeader, ConnectionOptions options, CancellationToken cancellationToken, IProgress<UploadProgressInfo> progress = null) { if(options == null) options = ConnectionOptions.Default; var req = new HttpRequestMessage(HttpMethod.Post, url); #if WIN_RT var httpContent = new HttpBufferContent(content.AsBuffer()); httpContent.Headers.ContentType = HttpMediaTypeHeaderValue.Parse(contentType); #else var httpContent = new ByteArrayContent(content); httpContent.Headers.ContentType = MediaTypeHeaderValue.Parse(contentType); #endif req.Content = httpContent; return ExecuteRequest(req, authorizationHeader, options, cancellationToken, progress); }
public async Task <Result <ItemAckPayloadResponse> > SendDirectPhotoAsync(InstaImage image, string threadId, long uploadId, Action <UploaderProgress> progress = null) { var upProgress = new UploaderProgress { Caption = string.Empty, UploadState = InstaUploadState.Preparing }; try { var entityName = "direct_" + uploadId; var uri = UriCreator.GetDirectSendPhotoUri(entityName); upProgress.UploadId = uploadId.ToString(); progress?.Invoke(upProgress); var ruploadParams = new JObject( new JProperty("media_type", 1), new JProperty("upload_id", uploadId.ToString()), new JProperty("upload_media_height", image.Height), new JProperty("upload_media_width", image.Width)); var requestMessage = new HttpRequestMessage(HttpMethod.Post, uri); requestMessage.Headers.Add("X-Entity-Name", entityName); requestMessage.Headers.Add("X-Instagram-Rupload-Params", ruploadParams.ToString(Formatting.None)); requestMessage.Headers.Add("Offset", "0"); var uploadBuffer = image.UploadBuffer; var content = new HttpBufferContent(uploadBuffer); content.Headers.ContentType = HttpMediaTypeHeaderValue.Parse("image/jpeg"); requestMessage.Headers.Add("X-Entity-Length", uploadBuffer.Length.ToString()); requestMessage.Content = content; upProgress.UploadState = InstaUploadState.Uploading; progress?.Invoke(upProgress); var response = await _httpClient.SendRequestAsync(requestMessage); var json = await response.Content.ReadAsStringAsync(); DebugLogger.LogResponse(response); var ruploadResp = JsonConvert.DeserializeObject <RuploadResponse>(json); if (response.StatusCode != HttpStatusCode.Ok || !ruploadResp.IsOk()) { upProgress.UploadState = InstaUploadState.Error; progress?.Invoke(upProgress); return(Result <ItemAckPayloadResponse> .Fail(json)); } var uploadIdResp = ruploadResp.UploadId; upProgress.UploadState = InstaUploadState.Uploaded; progress?.Invoke(upProgress); var configUri = UriCreator.GetDirectConfigPhotoUri(); var config = new Dictionary <string, string>(7) { ["action"] = "send_item", ["allow_full_aspect_ratio"] = "1", ["content_type"] = "photo", ["mutation_token"] = Guid.NewGuid().ToString(), ["sampled"] = "1", ["thread_id"] = threadId, ["upload_id"] = uploadIdResp }; response = await _httpClient.PostAsync(configUri, new HttpFormUrlEncodedContent(config)); json = await response.Content.ReadAsStringAsync(); DebugLogger.LogResponse(response); var obj = JsonConvert.DeserializeObject <ItemAckResponse>(json); if (response.StatusCode != HttpStatusCode.Ok || !obj.IsOk()) { upProgress.UploadState = InstaUploadState.Error; progress?.Invoke(upProgress); return(Result <ItemAckPayloadResponse> .Fail(json, obj.Message)); } upProgress.UploadState = InstaUploadState.Completed; progress?.Invoke(upProgress); return(Result <ItemAckPayloadResponse> .Success(obj.Payload, json, obj.Message)); } catch (Exception exception) { upProgress.UploadState = InstaUploadState.Error; progress?.Invoke(upProgress); DebugLogger.LogException(exception); return(Result <ItemAckPayloadResponse> .Except(exception)); } }
private async Task<VideoOperationResult> InvokeEmotionAPIForVideo(IBuffer buffer, string queryString) { VideoOperationResult result = null; Uri uri = new Uri($"{RecognitionUrl[RecognitionType.Video]}?{queryString}"); HttpBufferContent content = new HttpBufferContent(buffer); content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/octet-stream"); var response = await httpClient.PostAsync(uri, content); if (response.StatusCode == HttpStatusCode.Accepted) { string location = string.Empty; response.Headers.TryGetValue("Operation-Location", out location); if (string.IsNullOrEmpty(location) == false) { Uri operationUri = new Uri(location); var locationResponse = await httpClient.GetAsync(operationUri); string jsonResult = await locationResponse.Content.ReadAsStringAsync(); result = JsonConvert.DeserializeObject<VideoOperationResult>(jsonResult); ProcessVideoResult(result); if (result.Status == VideoOperationStatus.Running) { var task = MonitorVideoProgress(operationUri); } } } return result; }
async void Send(double dist, double longitude, double lattitude) { using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new Windows.Web.Http.Headers.HttpCredentialsHeaderValue("SharedAccessSignature", GetSASToken(sbNamespace, keyName, keyValue)); var buffer = Windows.Security.Cryptography.CryptographicBuffer.ConvertStringToBinary(dist.ToString() + ", " + longitude.ToString() + ", " + lattitude.ToString(), Windows.Security.Cryptography.BinaryStringEncoding.Utf8); HttpBufferContent BufferContent = new HttpBufferContent(buffer); BufferContent.Headers.Add("Content-Type", "application/atom+xml;type=entry;charset=utf-8"); var res = await client.PostAsync(new Uri("https://iacaddemo.servicebus.windows.net/iacaddemo/partitions/1/messages"), BufferContent); } }