public static string uploadPhoto(string file_location) { int timestamp = (int)(DateTime.Now - new DateTime(1970, 1, 1).ToLocalTime()).TotalSeconds; string upload_id = timestamp.ToString(); var requestContent = new MultipartFormDataContent(upload_id) { { new StringContent(upload_id), "\"upload_id\"" }, { new StringContent(Globals.uuid), "\"_uuid\"" }, { new StringContent(Globals.csrftoken), "\"_csrftoken\"" }, { new StringContent("{\"lib_name\":\"jt\",\"lib_version\":\"1.3.0\",\"quality\":\"87\"}"), "\"image_compression\"" } }; var imageContent = new ByteArrayContent(File.ReadAllBytes(file_location)); requestContent.Add(imageContent, "photo", $"pending_media_{upload_id}.jpg"); var client = new HttpClient(); using (var message = client.PostAsync(Constants.API_URLS[0] + "upload/photo/", requestContent)) { Console.WriteLine(message); } Console.WriteLine(Globals.LastResponse); configure(upload_id, imageContent.ToString(), ""); return(Globals.LastResponse); }
// Get the path and filename to process from the user. async void MakeAnalysisRequest(string imageFilePath) { HttpClient client = new HttpClient(); // Request headers. client.DefaultRequestHeaders.Add( "Ocp-Apim-Subscription-Key", subscriptionKey); // Request parameters. A third optional parameter is "details". string requestParameters = "returnFaceId=true&returnFaceLandmarks=false" + "&returnFaceAttributes=age,gender,headPose,smile,facialHair,glasses," + "emotion,hair,makeup,occlusion,accessories,blur,exposure,noise"; // Assemble the URI for the REST API Call. string uri = uriBase + "?" + requestParameters; HttpResponseMessage response; // Request body. Posts a locally stored JPEG image. byte[] byteData = GetImageAsByteArray(imageFilePath); using (ByteArrayContent content = new ByteArrayContent(byteData)) { // This example uses content type "application/octet-stream". // The other content types you can use are "application/json" // and "multipart/form-data". content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); Debug.Log(uri.ToString()); Debug.Log(content.ToString()); // Execute the REST API call. response = await client.PostAsync(uri, content); // Get the JSON response. string contentString = await response.Content.ReadAsStringAsync(); var objects = JArray.Parse(contentString); // Display the JSON response. print("\nResponse:\n"); print(contentString); staticMood.Clear(); foreach (JObject obj in objects) { staticMood.Add("happiness", float.Parse(obj["faceAttributes"]["emotion"]["happiness"].ToString())); float val = (obj["faceAttributes"]["gender"].ToString()) == "male" ? 1 : 0; float val1 = (obj["faceAttributes"]["glasses"].ToString()) == "ReadingGlasses" ? 1 : 0; staticMood.Add("gender", val); staticMood.Add("age", float.Parse(obj["faceAttributes"]["age"].ToString())); staticMood.Add("glasses", val1); staticMood.Add("sadness", float.Parse(obj["faceAttributes"]["emotion"]["sadness"].ToString())); staticMood.Add("surprise", float.Parse(obj["faceAttributes"]["emotion"]["surprise"].ToString())); } foreach (var item in staticMood) { Debug.Log(item.Key + " " + item.Value); } } }
static async void MakeRequest(string imageFilePath) { var client = new HttpClient(); // Request headers - replace this example key with your valid key. client.DefaultRequestHeaders.Add("3bcd830af74a48ddac52df8e635c795f", "259a781053d1435b8082930394a7e416"); // // NOTE: You must use the same region in your REST call as you used to obtain your subscription keys. // For example, if you obtained your subscription keys from westcentralus, replace "westus" in the // URI below with "westcentralus". string uri = "https://westus.api.cognitive.microsoft.com/emotion/v1.0/recognize?"; HttpResponseMessage response; string responseContent; // Request body. Try this sample with a locally stored JPEG image. byte[] byteData = GetImageAsByteArray(imageFilePath); using (var content = new ByteArrayContent(byteData)) { // This example uses content type "application/octet-stream". // The other content types you can use are "application/json" and "multipart/form-data". content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); response = await client.PostAsync(uri, content); responseContent = response.Content.ReadAsStringAsync().Result; MessageBox.Show(content.ToString()); MessageBox.Show(response.ToString()); } // A peek at the raw JSON response. MessageBox.Show(responseContent); // Processing the JSON into manageable objects. JToken rootToken = JArray.Parse(responseContent).First; // First token is always the faceRectangle identified by the API. JToken faceRectangleToken = rootToken.First; // Second token is all emotion scores. JToken scoresToken = rootToken.Last; // Show all face rectangle dimensions JEnumerable <JToken> faceRectangleSizeList = faceRectangleToken.First.Children(); foreach (var size in faceRectangleSizeList) { MessageBox.Show(size.ToString()); } // Show all scores JEnumerable <JToken> scoreList = scoresToken.First.Children(); foreach (var score in scoreList) { MessageBox.Show(score.ToString()); } }
public static async void ClientData(User authenticateUserData) { // string Baseurl = "http://localhost:55503/"; string Baseurl = ConfigurationManager.AppSettings["WebAPI"]; // List<LoginModel> EmpInfo = new List<LoginModel>(); using (var client = new HttpClient()) { //Passing service base url client.BaseAddress = new Uri(Baseurl); client.DefaultRequestHeaders.Clear(); //Define request data format client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //Sending request to find web api REST service resource GetAllEmployees using HttpClient //HttpResponseMessage Res = await client.GetAsync("api/LoginPost"); //var stringContent = new StringContent(model.ToString()); // var values = new Dictionary<string, string>(); // values.Add("ThisIs", "Annoying"); string json = JsonConvert.SerializeObject(authenticateUserData, Formatting.Indented); var buffer = System.Text.Encoding.UTF8.GetBytes(json); var byteContent = new ByteArrayContent(buffer); // byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); client.DefaultRequestHeaders.Add("Authorization", byteContent.ToString()); // //vg //client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", byteContent.ToString()); //client.DefaultRequestHeaders.Add("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{"user"}:{"pwd"}"))); //vg //client.DefaultRequestHeaders.Add("Authorization",buffer.ToString()); //client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken); // var httpResponce = Helper.Client.PostAsync(path, byteContent).Result; HttpResponseMessage Res = await client.PostAsync("api/AuthenticateUser", byteContent); //Checking the response is successful or not which is sent using HttpClient if (Res.IsSuccessStatusCode) { //Storing the response details recieved from web api var EmpResponse = Res.Content.ReadAsStringAsync().Result; //Deserializing the response recieved from web api and storing into the Employee list // EmpInfo = JsonConvert.DeserializeObject<List<LoginModel>>(EmpResponse); } } }
private async Task <VSMarketplaceItem> CoreRequest(string itemName) { var req = new ByteArrayContent(JsonSerializer.Serialize(new { filters = new[] { new { criteria = new[] { new { filterType = 7, value = itemName } } } }, flags = 914 })); req.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var result = await client.PostAsync(endpoint, req); if (result.IsSuccessStatusCode) { var response = await result.Content.ReadAsByteArrayAsync(); try { var extensions = JsonSerializer.Deserialize <VSMarketplaceResponse>(response); var raw = extensions.Results.FirstOrDefault()?.Extensions?.FirstOrDefault(); if (raw == null) { logger.LogInformation("Not found item: {itemName}", itemName); return(null); } var item = new VSMarketplaceItem(raw); await SaveCache(itemName, response, new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10) }); return(item); } catch (Exception ex) { ex.Data.Add("json", await result.Content.ReadAsStringAsync()); throw ex; } } var e = new InvalidCastException("Invalid extension data"); e.Data.Add("req", req.ToString()); e.Data.Add("res", await result.Content.ReadAsStringAsync()); throw e; }