public async Task PutGitHubFileAsync( string fileUrl, string commitMessage, string newFileContents) { Trace.TraceInformation($"Getting the 'sha' of the current contents of file '{fileUrl}'"); string currentFile = await _httpClient.GetStringAsync(fileUrl); string currentSha = JObject.Parse(currentFile)["sha"].ToString(); Trace.TraceInformation($"Got 'sha' value of '{currentSha}'"); Trace.TraceInformation($"Request to update file '{fileUrl}' contents to:"); Trace.TraceInformation(newFileContents); string updateFileBody = JsonConvert.SerializeObject(new { message = commitMessage, committer = new { name = _auth.User, email = _auth.Email }, content = ToBase64(newFileContents), sha = currentSha }, Formatting.Indented); var bodyContent = new StringContent(updateFileBody); using (HttpResponseMessage response = await _httpClient.PutAsync(fileUrl, bodyContent)) { response.EnsureSuccessStatusCode(); Trace.TraceInformation("Updated the file successfully."); } }
static void Main(string[] args) { using (var handler = new HttpClientHandler { UseDefaultCredentials = true }) { HttpClient httpClient = new HttpClient(handler); httpClient.DefaultRequestHeaders.Add("Accept", "application/json"); //tell the ServiceAPI we want a JSON response httpClient.BaseAddress = new Uri("http://localhost/ServiceAPI/"); // send some JSON and tell the request it is JSON via the mediaType parameter var content = new System.Net.Http.StringContent("{\"RecordRecordType\":{\"Uri\":2}, \"RecordTypedTitle\":\"Test Record\"}", Encoding.UTF8, "application/json"); HttpResponseMessage response = null; string responseJson = null; // run some async code inside a non-async method Task.Run(async() => { response = await httpClient.PostAsync("Record", content); responseJson = await response.Content.ReadAsStringAsync(); }).GetAwaiter().GetResult(); Console.WriteLine(responseJson); } }
/// <summary> /// 采用 raw 方式进行 Post, 推荐使用发送 JsonStr /// </summary> /// <param name="url">访问地址</param> /// <param name="data">传输数据 dynamic</param> /// <param name="encoding">设置编码码制 ( 默认UTF-8 )</param> /// <param name="timeout">设置超时 ( 默认30秒 )</param> /// <returns></returns> public static Task <string> HttpPostWithStringContent(string url, dynamic data, Encoding encoding = null, double timeout = s_TimeoutMilliseconds) { // TODO if (url.ToLower().StartsWith("https:")) { System.Net.ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback((sender, certificate, chain, sslPolicyErrors) => { return(true); }); } if (encoding == null) { encoding = Encoding.UTF8; } var client = new System.Net.Http.HttpClient(); client.Timeout = TimeSpan.FromMilliseconds(timeout); string postContent = string.Empty; if (data is string) { // postContent = data; postContent = data.ToString(); } else { postContent = Newtonsoft.Json.JsonConvert.SerializeObject(data); } System.Net.Http.StringContent httpContent = new System.Net.Http.StringContent(postContent, encoding, "application/json"); HttpResponseMessage resMsg = client.PostAsync(url, httpContent).Result; return(resMsg.Content.ReadAsStringAsync()); }
public async Task <Person> PostPersonToCloudCard(string json) { var serializer = new DataContractJsonSerializer(typeof(Person)); System.Diagnostics.Debug.WriteLine($"Posting the following JSON to /api/people: \n{json}\n"); StringContent content = new System.Net.Http.StringContent(json.ToString(), Encoding.UTF8, "application/json"); HttpResponseMessage response = await Client.PostAsync($"api/people?sendInvitation=false&allowUpdate=true&getLoginLink=true", content); //if ( response.IsSuccessStatusCode == false) //{ // throw new Exception("Invalid email address"); ////} //else //{ response.EnsureSuccessStatusCode(); //} string responseString = await response.Content.ReadAsStringAsync(); Stream stream = GenerateStreamFromString(responseString); Person person = serializer.ReadObject(stream) as Person; return(person); }
protected async void btnInsert_Click(object sender, EventArgs e) { int idRest = Convert.ToInt16(Session["idRest"]); HttpClient httpClient = new HttpClient(); httpClient.BaseAddress = new Uri(ip); Models.Mesa f = new Models.Mesa { Numero = textBoxNum.Text, Restaurante_id = idRest, Disponivel = true }; if (CheckBoxList1.SelectedItem.Text == "Sim") f.Disponivel = true; else if (CheckBoxList1.SelectedItem.Text == "Não") f.Disponivel = false; else f.Disponivel = true; string s = JsonConvert.SerializeObject(f); var content = new StringContent(s, Encoding.UTF8, "application/json"); await httpClient.PostAsync("/20131011110061/api/mesa", content); Reload(); }
public async Task UpdateUserAsync(UserUpdate userUpdate) { string url = string.Format("{0}/{1}", URL.RESTRoot, "user"); string authzHeader = AuthorizationHeader.CreateForREST(Config.ConsumerKey, Config.ConsumerSecret, AuthToken.Token, AuthToken.TokenSecret, url, "PUT"); string serializeObject = JsonConvert.SerializeObject(userUpdate); HttpContent httpContent = new StringContent(serializeObject); HttpRequestItem httpRequestItem = new HttpRequestItem() { URL = url, HttpMethod = HttpMethod.Put, AuthzHeader = authzHeader, HttpContent = httpContent, IsDataRequest = true }; HttpRequestHandler httpRequestHandler = new HttpRequestHandler(); string executeAsync = await httpRequestHandler.ReadAsStringAsync(httpRequestItem); //TODO : Investigate //return JsonConvert.DeserializeObject<User>(executeAsync); }
public static HttpResponseMessage CreateSuccessTokenResponseMessage() { HttpResponseMessage responseMessage = new HttpResponseMessage(HttpStatusCode.OK); HttpContent content = new StringContent("{\"token_type\":\"Bearer\",\"expires_in\":\"3599\",\"scope\":\"some-scope1 some-scope2\",\"access_token\":\"some-access-token\",\"refresh_token\":\"OAAsomethingencryptedQwgAA\",\"id_token\":\"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik1uQ19WWmNBVGZNNXBPWWlKSE1iYTlnb0VLWSIsImtpZCI6Ik1uQ19WWmNBVGZNNXBPWWlKSE1iYTlnb0VLWSJ9.eyJhdWQiOiJlODU0YTRhNy02YzM0LTQ0OWMtYjIzNy1mYzdhMjgwOTNkODQiLCJpc3MiOiJodHRwczovL2xvZ2luLm1pY3Jvc29mdG9ubGluZS5jb20vNmMzZDUxZGQtZjBlNS00OTU5LWI0ZWEtYTgwYzRlMzZmZTVlL3YyLjAvIiwiaWF0IjoxNDU1ODMzODI4LCJuYmYiOjE0NTU4MzM4MjgsImV4cCI6MTQ1NTgzNzcyOCwiaXBhZGRyIjoiMTMxLjEwNy4xNTkuMTE3IiwibmFtZSI6Ik1hcmlvIFJvc3NpIiwib2lkIjoidW5pcXVlX2lkIiwicHJlZmVycmVkX3VzZXJuYW1lIjoiZGlzcGxheWFibGVAaWQuY29tIiwic3ViIjoiSzRfU0dHeEtxVzFTeFVBbWhnNkMxRjZWUGlGemN4LVFkODBlaElFZEZ1cyIsInRpZCI6IjZjM2Q1MWRkLWYwZTUtNDk1OS1iNGVhLWE4MGM0ZTM2ZmU1ZSIsInZlciI6IjIuMCJ9.Z6Xc_PzqTtB-2TjyZwPpFGgkAs47m95F_I-NHxtIJT-H20i_1kbcBdmJaj7lMjHhJwAAMM-tE-iBVF9f7jNmsDZAADt-HgtrrXaXxkIKMwQ_MuB-OI4uY9KYIurEqmkGvOlRUK1ZVNNf7IKE5pqNTOZzyFDEyG8SwSvAmN-J4VnrxFz3d47klHoKVKwLjWJDj7edR2UUkdUQ6ZRj7YBj9UjC8UrmVNLBmvyatPyu9KQxyNyJpmTBT2jDjMZ3J1Z5iL98zWw_Ez0-6W0ti87UaPreJO3hejqQE_pRa4rXMLpw3oAnyEE1H7n0F6tK_3lJndZi9uLTIsdSMEXVnZdoHg\",\"id_token_expires_in\":\"3600\",\"profile_info\":\"eyJ2ZXIiOiIxLjAiLCJuYW1lIjoiTWFyaW8gUm9zc2kiLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJtYXJpb0BkZXZlbG9wZXJ0ZW5hbnQub25taWNyb3NvZnQuY29tIiwic3ViIjoiSzRfU0dHeEtxVzFTeFVBbWhnNkMxRjZWUGlGemN4LVFkODBlaElFZEZ1cyIsInRpZCI6IjZjM2Q1MWRkLWYwZTUtNDk1OS1iNGVhLWE4MGM0ZTM2ZmU1ZSJ9\"}"); responseMessage.Content = content; return responseMessage; }
private async void AppBarButton_Click(object sender, RoutedEventArgs e) { HttpClient httpClient = new HttpClient(); httpClient.BaseAddress = new Uri(ip); models.Autenticacao a = new models.Autenticacao { Login = login.Text, Senha = senha.Text }; string s = "=" + JsonConvert.SerializeObject(a); var content = new StringContent(s, Encoding.UTF8, "application/x-www-form-urlencoded"); var response = await httpClient.PostAsync("/api/user/login", content); var str = response.Content.ReadAsStringAsync().Result; str = "OK"; if (str == "OK") { this.Frame.Navigate(typeof(MainPage)); } }
private async Task <bool> LoginAuthAsync(string account, string password) { var httpClient = new System.Net.Http.HttpClient(); var urlStr = "http://xamarinclassdemo.azurewebsites.net/api/login"; httpClient.DefaultRequestHeaders.Add("username", account); httpClient.DefaultRequestHeaders.Add("password", password); var authContent = new System.Net.Http.StringContent(""); // var stringContent = new StringContent(Sb_json, UnicodeEncoding.UTF8, "application/json"); var result = await httpClient.PostAsync(urlStr, authContent); var resultStr = await result.Content.ReadAsStringAsync(); // await Task.Delay(500); // return true; // app直接進入BYPASS var returnValue = false; try { returnValue = bool.Parse(resultStr); } catch (FormatException ftEx) { await DisplayAlert("Err", ftEx.Message, "OK"); } return(returnValue); // app直接進入BYPASS }
public Task<string> Request(ApiClientRequest request) { if (request == null) throw new ArgumentNullException(nameof(request)); if (string.IsNullOrWhiteSpace(request.Username)) throw new ArgumentException("Username is required", nameof(request)); if (string.IsNullOrWhiteSpace(request.Password)) throw new ArgumentException("Password is required", nameof(request)); if (string.IsNullOrWhiteSpace(request.BaseAddress)) throw new ArgumentException("BaseAddress is required", nameof(request)); if (string.IsNullOrWhiteSpace(request.RequestUri)) throw new ArgumentException("RequestUri is required", nameof(request)); if (string.IsNullOrWhiteSpace(request.Content)) throw new ArgumentException("Content is required", nameof(request)); using (var httpClient = CreateHttpClient(request.Username, request.Password, request.BaseAddress)) using (var content = new StringContent(request.Content, Encoding.UTF8, "application/soap+xml")) { var response = httpClient.PostAsync(request.RequestUri, content).Result; if (!response.IsSuccessStatusCode) { var error = response.Content.ReadAsStringAsync().Result; throw new InvalidOperationException($"{error} ({response.StatusCode} {response.ReasonPhrase})"); } return response .Content .ReadAsStringAsync(); } }
public async Task<JObject> Execute() { if (!NetworkInterface.GetIsNetworkAvailable()) throw new Exception("Network is not available."); var uri = GetFullUri(_parameters); var request = WebRequest.CreateHttp(uri); request.Method = _method; Debug.WriteLine("Invoking " + uri); JObject response = null; var httpClient = new HttpClient(); if (_method == "GET") { HttpResponseMessage responseMessage = await httpClient.GetAsync(uri); string content = await responseMessage.Content.ReadAsStringAsync(); if (!string.IsNullOrEmpty(content)) response = JObject.Parse(content); } else if (_method == "POST") { var postContent = new StringContent(_postParameters.ConstructQueryString()); postContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); HttpResponseMessage responseMessage = await httpClient.PostAsync(uri, postContent); string content = await responseMessage.Content.ReadAsStringAsync(); if (!string.IsNullOrEmpty(content)) response = JObject.Parse(content); } return response; }
private static void MakeConfigRequest() { using (HttpClient httpClient = new HttpClient()) { httpClient.BaseAddress = new Uri(BridgeBaseAddress); var content = new StringContent( CreateConfigRequestContentAsJson(), Encoding.UTF8, "application/json"); try { var response = httpClient.PostAsync("/config/", content).GetAwaiter().GetResult(); if (!response.IsSuccessStatusCode) { string reason = String.Format("{0}Bridge returned unexpected status code='{1}', reason='{2}'", Environment.NewLine, response.StatusCode, response.ReasonPhrase); if (response.Content != null) { string contentAsString = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); reason = String.Format("{0}, content:{1}{2}", reason, Environment.NewLine, contentAsString); } throw new Exception(reason); } _BridgeStatus = BridgeState.Started; } catch (Exception exc) { _BridgeStatus = BridgeState.Faulted; throw new Exception("Bridge is not running", exc); } } }
public async Task CheckIfObjectIsDeserializedWithoutErrors() { // Arrange var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var client = server.CreateClient(); var sampleId = 2; var sampleName = "SampleUser"; var sampleAlias = "SampleAlias"; var sampleDesignation = "HelloWorld"; var sampleDescription = "sample user"; var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<User xmlns=\"http://schemas.datacontract.org/2004/07/FormatterWebSite\"><Id>" + sampleId + "</Id><Name>" + sampleName + "</Name><Alias>" + sampleAlias + "</Alias>" + "<Designation>" + sampleDesignation + "</Designation><description>" + sampleDescription + "</description></User>"; var content = new StringContent(input, Encoding.UTF8, "application/xml"); // Act var response = await client.PostAsync("http://localhost/Validation/Index", content); //Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("User has been registerd : " + sampleName, await response.Content.ReadAsStringAsync()); }
// ReSharper disable once InconsistentNaming public async void Controller_Can_POST_a_new_Registerd_User() { using (var client = new HttpClient()) { // Arrange client.BaseAddress = new Uri(UrlBase); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // Manually set "content-type" header to reflect serialized data format. var settings = new JsonSerializerSettings(); var ser = JsonSerializer.Create(settings); var j = JObject.FromObject(_registration, ser); HttpContent content = new StringContent(j.ToString()); content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); // Act // PostAsJsonAsync(), per MS recommendation, however results in problem of RegisterAsync() accepting payload: content type? // Serialized registration data is now associated with HttpContent element explicitly, with format then set. var response = await client.PostAsync(client.BaseAddress + "/RegisterAsync", content); //var response = await client.PostAsJsonAsync(client.BaseAddress + "/RegisterAsync", _registration); // error // Assert Assert.IsTrue(response.StatusCode == HttpStatusCode.Created); Assert.IsTrue(response.IsSuccessStatusCode); } }
public void Authenticate() { using (var client = new HttpClient()) { client.BaseAddress = new Uri(webServiceRootPath); var content = new StringContent( string.Format("grant_type=password&username={0}&password={1}", login.Replace("@", "%40"), password), Encoding.UTF8, "text/plain"); client.Timeout = TimeSpan.FromSeconds(30); var response = client.PostAsync("Token", content).Result; if (!response.IsSuccessStatusCode) { throw new Exception("Authentication failed " + FormatHttpError(response)); } string serialized = response.Content.ReadAsStringAsync().Result; var model = JsonConvert.DeserializeObject<TokenResponseModel>(serialized); if (!"bearer".Equals(model.TokenType, StringComparison.InvariantCultureIgnoreCase)) { throw new Exception("Returned token is not of bearer type, actual: " + model.TokenType); } token = model.AccessToken; } }
private async Task <HttpResponseMessage> PostAsJsonAsync <T>(HttpClient client, string requestUri, T value) { string contentString = Newtonsoft.Json.JsonConvert.SerializeObject(value); StringContent content = new System.Net.Http.StringContent(contentString, Encoding.UTF8, "application/json"); return(await client.PostAsync(requestUri, content)); }
public async Task<bool> AddToFavorite(Recipe r) { try { string json = JsonConvert.SerializeObject(r); HttpContent content = new StringContent(json, Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.PostAsync("api/recipes", content); if ((response.IsSuccessStatusCode) || (response.StatusCode.ToString().Equals("Conflict"))) { String recipeId = r.recipe_id + currentApp.GlobalInstance.userId; UserFavorite uFav = new UserFavorite(recipeId, currentApp.GlobalInstance.userId, r.recipe_id); string jsonfav = JsonConvert.SerializeObject(uFav); HttpContent contentfav = new StringContent(jsonfav, Encoding.UTF8, "application/json"); HttpResponseMessage responsefav = await client.PostAsync("api/userfavorites", contentfav); if (responsefav.IsSuccessStatusCode) { return true; } return false; } } catch (HttpRequestException e) { return false; } return false; }
public void CreateEvent(Guid eventId, string eventType = "DetailsView") { var @event = new { EventId = eventId, Timestamp = DateTimeFactory.Now().ToString("O"), EventType = eventType }; var eventJson = JsonConvert.SerializeObject(@event, _jsonSettings); var requestContent = new StringContent(eventJson, Encoding.UTF8, "application/json"); var request = new HttpRequestMessage(HttpMethod.Post, "/events") { Content = requestContent }; var response = _httpClient.SendAsync(request); try { var result = response.Result; var statusCode = result.StatusCode; if (statusCode == HttpStatusCode.Created) { return; } RaiseResponseError(request, result); } finally { Dispose(request, response); } }
private static void MakeConfigRequest() { using (HttpClient httpClient = new HttpClient()) { httpClient.BaseAddress = new Uri(BridgeBaseAddress); string resourceFolder = TestProperties.GetProperty(TestProperties.BridgeResourceFolder_PropertyName); string contentPayload = "{ resourcesDirectory : \"" + resourceFolder + "\" }"; var content = new StringContent( contentPayload, Encoding.UTF8, "application/json"); try { var response = httpClient.PostAsync("/config/", content).Result; if (!response.IsSuccessStatusCode) throw new Exception("Unexpected status code: " + response.StatusCode); _BridgeStatus = BridgeState.Started; } catch (Exception exc) { _BridgeStatus = BridgeState.Faulted; throw new Exception("Bridge is not running", exc); } } }
private static string MakeResourcePutRequest(string resourceName) { using (HttpClient httpClient = new HttpClient()) { httpClient.BaseAddress = new Uri(BridgeBaseAddress); var content = new StringContent( string.Format(@"{{ name : ""{0}"" }}", resourceName), Encoding.UTF8, "application/json"); try { var response = httpClient.PutAsync("/resource/", content).Result; if (!response.IsSuccessStatusCode) throw new Exception("Unexpected status code: " + response.StatusCode); var responseContent = response.Content.ReadAsStringAsync().Result; var match = regexResource.Match(responseContent); if (!match.Success || match.Groups.Count != 2) throw new Exception("Invalid response from bridge: " + responseContent); return match.Groups[1].Value; } catch (Exception exc) { throw new Exception("Unable to start resource: " + resourceName, exc); } } }
public void ProcessBatchAsync_CallsRegisterForDispose() { List<IDisposable> expectedResourcesForDisposal = new List<IDisposable>(); MockHttpServer server = new MockHttpServer(request => { var tmpContent = new StringContent(String.Empty); request.RegisterForDispose(tmpContent); expectedResourcesForDisposal.Add(tmpContent); return new HttpResponseMessage { Content = new StringContent(request.RequestUri.AbsoluteUri) }; }); UnbufferedODataBatchHandler batchHandler = new UnbufferedODataBatchHandler(server); HttpRequestMessage batchRequest = new HttpRequestMessage(HttpMethod.Post, "http://example.com/$batch") { Content = new MultipartContent("mixed") { ODataBatchRequestHelper.CreateODataRequestContent(new HttpRequestMessage(HttpMethod.Get, "http://example.com/")), new MultipartContent("mixed") // ChangeSet { ODataBatchRequestHelper.CreateODataRequestContent(new HttpRequestMessage(HttpMethod.Post, "http://example.com/")) } } }; var response = batchHandler.ProcessBatchAsync(batchRequest, CancellationToken.None).Result; var resourcesForDisposal = batchRequest.GetResourcesForDisposal(); foreach (var expectedResource in expectedResourcesForDisposal) { Assert.Contains(expectedResource, resourcesForDisposal); } }
public async Task <ActionResult> Recargar() { string parajson = "clave"; var json = JsonConvert.SerializeObject(parajson); var jsonContent = new System.Net.Http.StringContent(json, UnicodeEncoding.UTF8, "application/json"); var guidResponse = await GlobalVariables.WebApiClient.GetStringAsync("https://localhost:44343/api/main/GuidSala/" + username + "/" + receptor); if (guidResponse == "") //aun no hay sala con esa persona { var response = GlobalVariables.WebApiClient.PostAsync("https://localhost:44343/api/main/NuevaSala/" + username + "/" + receptor, jsonContent).Result; List <string> mensajes = new List <string>(); Response.Write("<script>alert('Aun no tiene mensajes con este usuario')</script>"); ViewBag.Amigo = receptor; return(View(mensajes)); } else // ya hay una sala, recuperar mensajes y mandarlos a vista chat { var response = await GlobalVariables.WebApiClient.GetStringAsync("https://localhost:44343/api/main/Recuperar/" + guidResponse + "/" + username); var mensajesDesEncriptados = JsonConvert.DeserializeObject <List <Mensaje> >(response); List <string> mensajes = new List <string>(); foreach (var item in mensajesDesEncriptados) { mensajes.Add(item.UsuarioEmisor + ": " + item.Contenido); } ViewBag.Amigo = receptor; return(View("Chat", mensajes)); } }
public void WriteMessageAsync_WritesResponseMessage() { MemoryStream ms = new MemoryStream(); HttpContent content = new StringContent(String.Empty, Encoding.UTF8, "multipart/mixed"); content.Headers.ContentType.Parameters.Add(new NameValueHeaderValue("boundary", Guid.NewGuid().ToString())); IODataResponseMessage odataResponse = new ODataMessageWrapper(ms, content.Headers); var batchWriter = new ODataMessageWriter(odataResponse).CreateODataBatchWriter(); HttpResponseMessage response = new HttpResponseMessage() { Content = new StringContent("example content", Encoding.UTF8, "text/example") }; response.Headers.Add("customHeader", "bar"); batchWriter.WriteStartBatch(); ODataBatchResponseItem.WriteMessageAsync(batchWriter, response).Wait(); batchWriter.WriteEndBatch(); ms.Position = 0; string result = new StreamReader(ms).ReadToEnd(); Assert.Contains("example content", result); Assert.Contains("text/example", result); Assert.Contains("customHeader", result); Assert.Contains("bar", result); }
/// <summary> /// Sets the content of the request by the given body and the the required GZip configuration. /// </summary> /// <param name="request">The request.</param> /// <param name="service">The service.</param> /// <param name="body">The body of the future request. If <c>null</c> do nothing.</param> /// <param name="gzipEnabled"> /// Indicates if the content will be wrapped in a GZip stream, or a regular string stream will be used. /// </param> internal static void SetRequestSerailizedContent(this HttpRequestMessage request, IClientService service, object body, bool gzipEnabled) { if (body == null) { return; } HttpContent content = null; var mediaType = "application/" + service.Serializer.Format; var serializedObject = service.SerializeObject(body); if (gzipEnabled) { content = CreateZipContent(serializedObject); content.Headers.ContentType = new MediaTypeHeaderValue(mediaType) { CharSet = Encoding.UTF8.WebName }; } else { content = new StringContent(serializedObject, Encoding.UTF8, mediaType); } request.Content = content; }
private static void SendSampleData() { try { var sampleData = new { value = "Sending some test info" + DateTime.Now.ToString() }; HttpClient httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var data = string.Format("Sending data on {0}", DateTime.Now.ToLongTimeString()); var jsonData = string.Format("{{'sender': '{0}', 'message': '{1}' }}", Environment.MachineName, data); var stringContent = new StringContent(jsonData, Encoding.UTF8, "application/json"); HttpResponseMessage response = null; response = httpClient.PostAsync(ConfigurationManager.AppSettings["serverAdress"] + "/api/data", stringContent).Result; if (response.IsSuccessStatusCode) { Console.WriteLine("Post succesful, StatusCode: " + response.StatusCode); } else { Console.WriteLine("Post failed, StatusCode: " + response.StatusCode); } } catch (Exception ex) { Console.Write(ex.Message + ex.StackTrace); } }
/// <summary> /// Send events to Seq. /// </summary> /// <param name="events">The buffered events to send.</param> protected override void SendBuffer(LoggingEvent[] events) { if (ServerUrl == null) return; var payload = new StringWriter(); payload.Write("{\"events\":["); LoggingEventFormatter.ToJson(events, payload); payload.Write("]}"); var content = new StringContent(payload.ToString(), Encoding.UTF8, "application/json"); if (!string.IsNullOrWhiteSpace(ApiKey)) content.Headers.Add(ApiKeyHeaderName, ApiKey); var baseUri = ServerUrl; if (!baseUri.EndsWith("/")) baseUri += "/"; using (var httpClient = new HttpClient { BaseAddress = new Uri(baseUri) }) { var result = httpClient.PostAsync(BulkUploadResource, content).Result; if (!result.IsSuccessStatusCode) ErrorHandler.Error(string.Format("Received failed result {0}: {1}", result.StatusCode, result.Content.ReadAsStringAsync().Result)); } }
async private void button_Click(object sender, RoutedEventArgs e) { using (var httpClient = new HttpClient()) { //httpClient.BaseAddress = new Uri("http://alarm.fr.to/"); httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "YW5vbnltb3VzOmFub255bW91cw=="); var message = new { arrivalTime = textBox.Text, breakfastTime = textBox1.Text }; var json_object = JsonConvert.SerializeObject(message); HttpContent content = new StringContent(json_object.ToString(), Encoding.UTF8); content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); //HttpResponseMessage response = httpClient.PostAsync("api", content).Result; var response = await httpClient.PostAsync("http://alarm.fr.to/api", content); //string statusCode = response.StatusCode.ToString(); //response.EnsureSuccessStatusCode(); //Task<string> responseBody = response.Content.ReadAsStringAsync(); } }
public bool TelemetryIngest(Telemetry telemetry) { string serviceBusNamespace = "iotmc-ns"; string serviceBusUri = string.Format("{0}.servicebus.windows.net", serviceBusNamespace); string eventHubName = "IoTMC"; string eventHubSASKeyName = "Device01"; string eventHubSASKey = "t0JK19v94H3R8yAZ1uVkGcIUFi8zmGmBts4N09aNI0s="; using (HttpClient httpClient = new HttpClient()) { httpClient.BaseAddress = new Uri(String.Format("https://{0}", serviceBusUri)); httpClient.DefaultRequestHeaders.Accept.Clear(); string sBToken = CreateServiceBusSASToken(eventHubSASKeyName, eventHubSASKey, serviceBusUri); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("SharedAccessSignature", sBToken); HttpContent httpContent = new StringContent(telemetry.asJson(), Encoding.UTF8); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); string ingestPath = String.Format("/{0}/publishers/device01/messages", eventHubName); Task<HttpResponseMessage> response = httpClient.PostAsync(ingestPath, httpContent); response.Wait(); if (response.Result.IsSuccessStatusCode) { return true; } return false; } }
public static HttpResponseMessage CreateInvalidGrantTokenResponseMessage() { HttpResponseMessage responseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest); HttpContent content = new StringContent("{\"error\":\"invalid_grant\",\"error_description\":\"AADSTS70002: Error validating credentials.AADSTS70008: The provided access grant is expired or revoked.Trace ID: f7ec686c-9196-4220-a754-cd9197de44e9Correlation ID: 04bb0cae-580b-49ac-9a10-b6c3316b1eaaTimestamp: 2015-09-16 07:24:55Z\",\"error_codes\":[70002,70008],\"timestamp\":\"2015-09-16 07:24:55Z\",\"trace_id\":\"f7ec686c-9196-4220-a754-cd9197de44e9\",\"correlation_id\":\"04bb0cae-580b-49ac-9a10-b6c3316b1eaa\"}"); responseMessage.Content = content; return responseMessage; }
public async Task<Result> PostData(Uri uri, MultipartContent header, StringContent content) { var httpClient = new HttpClient(); try { if (!string.IsNullOrEmpty(AuthenticationToken)) { httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AuthenticationToken); } HttpResponseMessage response; if (header == null) { if(content == null) content = new StringContent(string.Empty); response = await httpClient.PostAsync(uri, content); } else { response = await httpClient.PostAsync(uri, header); } var responseContent = await response.Content.ReadAsStringAsync(); return new Result(response.IsSuccessStatusCode, responseContent); } catch (Exception ex) { throw new WebException("Kinder Chat API Error: Service error", ex); } }
public async Task SendNotification(string titre, string message, NotificationClient client) { string URL = "https://android.googleapis.com/gcm/send"; string SERVER_API_KEY = System.Environment.GetEnvironmentVariable("SERVER_API_KEY"); var encodedMessage = System.Net.WebUtility.UrlEncode(message); var encodedTitle = System.Net.WebUtility.UrlEncode(titre); HttpClient httpClient = new HttpClient(); httpClient.BaseAddress = new Uri(URL); httpClient.DefaultRequestHeaders .Accept .Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded")); httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", string.Format("key={0}", SERVER_API_KEY)); string deviceId = client.NotificationID; string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.title=" + encodedTitle + "&data.message=" + encodedMessage + "&data.time=" + System.DateTime.Now.ToString() + "®istration_id=" + deviceId + ""; var content = new StringContent(postData, Encoding.UTF8, "application/x-www-form-urlencoded"); HttpResponseMessage response = await httpClient.PostAsync(URL, content); var responseString = await response.Content.ReadAsStringAsync(); if (response.StatusCode != System.Net.HttpStatusCode.OK) { _logger.Error("Error while sending Android notification. Return code is " + response.StatusCode + ". Content is " + response.Content); } else if(responseString.Contains("NotRegistered")) { _logger.Error("Error while sending Android notification. Device is not registered"); } else { _logger.Debug("Android notification OK. Content is " + responseString); } }
public static byte[] PostJsonBodyReturnBytes(string url, IDictionary <string, object> values, Encoding encoding = null, IDictionary <string, string> headers = null, string referrer = null, string accept = null) { var client = SetupClient(headers, referrer, accept); var json = values == null || values.Count < 1 ? "" : Newtonsoft.Json.JsonConvert.SerializeObject(values, JsonDatetimeSetting); var content = new System.Net.Http.StringContent(json ?? "", encoding ?? Encoding.UTF8); content.Headers.ContentType.CharSet = (encoding ?? Encoding.UTF8).BodyName; content.Headers.ContentType.MediaType = "application/json"; HttpResponseMessage ret = null; try { ret = client.PostAsync(url, content).Result; } catch (Exception ex) { throw GetOrignalException(ex); } if (ret.IsSuccessStatusCode == false) { throw new Exception("HTTP请求错误:" + ret.StatusCode); } var data = ret.Content.ReadAsByteArrayAsync().Result; return(data); }
/// <summary> /// Retrieves and stores an authentication token. Tokens are valid for 10 minutes only. /// </summary> public async Task EnsureValidToken() { if (DateTime.Now <= this.tokenValidUntil) { return; } Debug.WriteLine("Token expired. Getting new one."); this.tokenValidUntil = this.tokenValidUntil.AddMinutes(9); using (var client = new HttpClient()) { var request = new StringContent(this.requestDetails); request.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); var response = await client.PostAsync(DATAMARKET_ACCESS_URI, request); // Spit out token in string represantation for debugging purposes. var tokenString = await response.Content.ReadAsStringAsync(); Debug.WriteLine(tokenString); // Now get as stream and deserialize JSON to an object. using (var webResponse = await response.Content.ReadAsStreamAsync()) { var serializer = new DataContractJsonSerializer(typeof(AdmAccessToken)); this.Token = (AdmAccessToken)serializer.ReadObject(webResponse); } } }
public async Task<OperationResult<PageResult<product>>> GetHighwaveProduct(string accessToken, string[] brands, DateTime start, DateTime? end = null, int pageIndex = 1, int pageSize = 20) { string requestUrl = string.Format(url + @"/highwave/GetProduct?pageIndex={0}&pageSize={1}", pageIndex, pageSize); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authorizationScheam, accessToken); var postString = new StringContent(JsonConvert.SerializeObject(new { brands = brands, start = start, end = end })); postString.Headers.ContentType.MediaType = contentType; var result = await client.PostAsync(requestUrl, postString); if (result.StatusCode != HttpStatusCode.OK) { var errorStr = await result.Content.ReadAsStringAsync(); var error = JsonConvert.DeserializeObject<OperationResult>(errorStr); return new OperationResult<PageResult<Models.product>>() { err_code = error.err_code, err_info = error.err_info }; } var Json = result.Content.ReadAsStringAsync().Result; PageResult<product> product = JsonConvert.DeserializeObject<PageResult<product>>(Json); return new OperationResult<PageResult<product>>() { err_code = ErrorEnum.success, err_info = ErrorEnum.success.ToString(), entity = product }; }
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { return await Task.Run(() => { var metadata = _metadataProvider.GetMetadata(request); if (request.Headers.Any(h => h.Key == "X-Proxy-Type" && h.Value.Contains("metadata"))) return request.CreateResponse(System.Net.HttpStatusCode.OK, metadata); var template = new JsProxyTemplate(metadata); var js = new StringContent(template.TransformText()); js.Headers.ContentType = new MediaTypeHeaderValue("application/javascript"); return new HttpResponseMessage { Content = js }; ; }); }
public HttpResponseMessage GetEntity(string filename) { var content = new StringContent(File.ReadAllText(Path.Combine("API/Entities", filename)), Encoding.UTF8); var response = new HttpResponseMessage(); response.Content = content; return response; }
virtual protected async Task <Response> CreateRequest <Response>( string url, net.HttpMethod method, object input, string token) { return(await CreateRequestMessage(url, method, token, async (msg) => { if (input is Stream stream) { using (var content = new net.StreamContent(stream)) { content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); msg.Content = content; return await GetResult <Response>(msg); } } else { var stringContent = input is string?(string)input : JObject.FromObject(input).ToString(); using (var content = new net.StringContent(stringContent)) { content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); msg.Content = content; return await GetResult <Response>(msg); } } })); }
public async Task <List <ProductoEspecificoDto> > ProductosPublicacionFiltro(string filtro)//recibir el offset por parametro. { var db = new QueryFactory(conexion, SqlKataCompiler); var Productos = db.Query("Publicaciones"). Select("ProductoID").Get <int>().ToList(); var Publicaciones = db.Query("Publicaciones"). Select("ID").Get <int>().ToList(); List <ProductoEspecificoDto> posts = null; JsonProductoFiltroDto jsonDTO = new JsonProductoFiltroDto(); jsonDTO.productosID = Productos; jsonDTO.filtro = filtro; jsonDTO.publicacionesID = Publicaciones; string url = "https://localhost:44370/api/Producto/ProductosPublicacionesFiltro"; using (var httpClient = new HttpClient()) { var json = Newtonsoft.Json.JsonConvert.SerializeObject(jsonDTO, Formatting.None); var data = new System.Net.Http.StringContent(json, Encoding.UTF8, "application/json"); var result = await httpClient.PostAsync(url, data); string resultado = result.Content.ReadAsStringAsync().Result; posts = JsonConvert.DeserializeObject <List <ProductoEspecificoDto> >(resultado); } return(posts); }
protected bool Put <TObject>(string requestAdress, TObject objectToPut) { string strJson = JsonConvert.SerializeObject(objectToPut); StringContent content = new System.Net.Http.StringContent(strJson, Encoding.UTF8, "application/json"); HttpResponseMessage response = httpClient.PutAsync(requestAdress, content).Result; return(response.IsSuccessStatusCode); }
protected async Task <TOutput> Create <TOutput>(object model, string resourceUrl) { var serialized = JsonConvert.SerializeObject(model, DefaultCreateSettings); var httpConent = new System.Net.Http.StringContent(serialized); var result = await _client.PostAsync(resourceUrl, httpConent); return(JsonConvert.DeserializeObject <TOutput>(await result.Content.ReadAsStringAsync(), DefaultSettings)); }
private async Task <string> CallWorkflow(WorkflowConfig workflow, ByteString data) { var req = new HttpRequestMessage(HttpMethod.Post, "http://localhost/workflow"); var content = new System.Net.Http.StringContent(data.ToStringUtf8(), Encoding.UTF8, "application/json"); req.Content = content; var flowConfig = this.workflowEngine.Config; var flowName = workflow.Name; flowConfig.FlowEdgeEnvironmentEndpointUri = new Uri("http://localhost"); using (RequestCorrelationContext.Current.Initialize(apiVersion: FlowConstants.PrivatePreview20190601ApiVersion, localizationLanguage: "en-us")) { var clientRequestIdentity = new RequestIdentity { Claims = new Dictionary <string, string>(), IsAuthenticated = true, }; clientRequestIdentity.AuthorizeRequest(RequestAuthorizationSource.Direct); RequestCorrelationContext.Current.SetAuthenticationIdentity(clientRequestIdentity); var flow = await FindExistingFlow(workflow.Name); var triggerName = flow.Definition.Triggers.Keys.Single(); var trigger = flow.Definition.GetTrigger(triggerName); var ct = CancellationToken.None; if (trigger.IsFlowRecurrentTrigger() || trigger.IsNotificationTrigger()) { await this.workflowEngine.Engine .RunFlowRecurrentTrigger( flow : flow, flowName : flowName, triggerName : triggerName); return(""); } else { var triggerOutput = this.workflowEngine.Engine.GetFlowHttpEngine().GetOperationOutput(req, flowConfig.EventSource, ct).Result; var resp = await this.workflowEngine.Engine .RunFlowPushTrigger( request : req, context : new FlowDataPlaneContext(flow), trigger : trigger, subscriptionId : EdgeFlowConfiguration.EdgeSubscriptionId, resourceGroup : EdgeFlowConfiguration.EdgeResourceGroupName, flowName : flowName, triggerName : triggerName, triggerOutput : triggerOutput, clientCancellationToken : ct); return(await resp.Content.ReadAsStringAsync()); } } }
public static string Register(string datasetId) { Newtonsoft.Json.Schema.Generation.JSchemaGenerator jsonGen = new Newtonsoft.Json.Schema.Generation.JSchemaGenerator(); jsonGen.DefaultRequired = Newtonsoft.Json.Required.Default; var registration = new { name = "Rozhodnuti UOHS", //povinne, verejne jmeno datasetu datasetId = datasetId, //nepovinne, doporucujeme uvest. Jednoznacny identifikator datasetu v URL a ve volani API origUrl = "http://www.uohs.cz/cs/verejne-zakazky/sbirky-rozhodnuti/", //zdroj dat datasetu jsonSchema = jsonGen.Generate(typeof(UOHSData)), //JSON schema betaversion = true, // pokud true, pak dataset neni videt v seznam datasetu na HlidacStatu.cz/data allowWriteAccess = false, // pokud true, pak data v datasetu muze kdokoliv přepsat nebo smazat. Stejně tak údaje v registraci. // pokud false, pak kdokoliv muze data pridat, ale nemuze je prepsat či smazat orderList = new string[, ] { { "Nabytí právní moci", "PravniMoc" }, { "Účastníci", "Ucastnici.Jmeno" } }, }; HttpClient httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Add("Authorization", apiToken); string jsonResult = httpClient.GetAsync(apiRoot + "/Datasets/" + registration.datasetId) .Result.Content .ReadAsStringAsync().Result; var result = JContainer.Parse(jsonResult); if (result.HasValues == true) //dataset uz existuje { //smazu ho //zde uvedeno jako priklad, jsonResult = httpClient.DeleteAsync(apiRoot + "/Datasets/" + registration.datasetId) .Result.Content .ReadAsStringAsync().Result; } //vytvoreni nove registrace var content = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(registration)); jsonResult = httpClient.PostAsync(apiRoot + "/Datasets", content) .Result.Content .ReadAsStringAsync().Result; result = JObject.Parse(jsonResult); if (result["error"] == null) { Console.WriteLine("Zaregistrovan dataset " + result["datasetId"].Value <string>()); return(result["datasetId"].Value <string>()); } else { Console.WriteLine("Chyba " + result["error"]["description"]); return(null); } }
public string PutSync(string addr, string postJson) { var client = CreateClient(); System.Net.Http.HttpContent httpContent = new System.Net.Http.StringContent(postJson, Encoding.UTF8, "application/json"); var t = GetResult(client.PutAsync(addr, httpContent)); return(t); }
protected async Task <HttpResponseMessage> Post <RequestType>(UriParameter UriParameters, RequestType BodyParameters = default(RequestType), [CallerMemberName] string MethodName = null, string ControllerName = null) { var json = Newtonsoft.Json.JsonConvert.SerializeObject(BodyParameters); System.Net.Http.StringContent content = new System.Net.Http.StringContent(json, Encoding.UTF8, "application/json"); var result = await this.httpClient.PostAsync(UrlGenerator(UriParameters, MethodName, ControllerName), content); return(result); }
public static string Update(this HttpClient client, string jsonValue) { StringContent content = new System.Net.Http.StringContent(jsonValue, Encoding.UTF8, "application/json"); var responseMessage = client.PutAsync("", content).Result; var result = responseMessage.Content.ReadAsStringAsync().Result; return(result); }
private async void sendRequest(string json) { using (var requestMessage = new HttpRequestMessage(HttpMethod.Post, _url)) { //requestMessage.Headers.Authorization = new AuthenticationHeaderValue(scheme, authorization); var content = new System.Net.Http.StringContent(json, Encoding.UTF8, "application/json"); requestMessage.Content = content; var reponse = await _client.SendAsync(requestMessage); } }
public async Task SetBuildResultAsync(Guid buildQueueID, BuildResult result) { var json = Newtonsoft.Json.JsonConvert.SerializeObject(result); var content = new System.Net.Http.StringContent(json, Encoding.UTF8, "application/json"); var response = await _client.PostAsync(BuildRequestUrl($"api/BuildResult/{buildQueueID}"), content); response.EnsureSuccessStatusCode(); }
public async Task PostAsync(string payload, string path) { Console.WriteLine($"Preparing payload of: {payload} to {this.baseUrl + path}."); HttpContent contentPost = new System.Net.Http.StringContent(payload, Encoding.UTF8, "application/json"); var response = await this.httpClient.PostAsync(this.baseUrl + path, contentPost); var responseString = await response.EnsureSuccessStatusCode().Content.ReadAsStringAsync(); Console.WriteLine($"Received: {responseString}."); }
public async void TestPost() { var json = JsonConvert.SerializeObject(NoteSixForPosting); var stringContent = new System.Net.Http.StringContent(json, UnicodeEncoding.UTF8, "application/json"); var response = await _client.PostAsync("/api/Data/PostData", stringContent); var responsedata = response.StatusCode; Assert.Equal(HttpStatusCode.Created, responsedata); }
public AuthorizationRequest(NetworkIPSConfig environment) : base(HttpMethod.Post, "/identity/auth/access-token") { Headers.Clear(); Headers.Add("accept", "application/vnd.ni-identity.v1+json"); Headers.Authorization = new AuthenticationHeaderValue("Basic", environment.ApiKey); var f = new System.Net.Http.StringContent("{\"realmName\":\"ni\"}", Encoding.UTF8, "application/json"); this.Content = f; this.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.ni-identity.v1+json"); }
public static async Task <JObject> PostContact(Contact contact) { var modifiedtask = ModifyContact(contact); var client = new HttpClient(); var data = Newtonsoft.Json.JsonConvert.SerializeObject(contact); var content = new System.Net.Http.StringContent(data, System.Text.Encoding.UTF8, "application/json"); var response = await client.PostAsync(API.ContactsAPI, content); response.EnsureSuccessStatusCode(); return(response.Content.ReadAsAsync <JObject>().Result); }
//public async Task<T> Post<T>(string urlArguments, MultipartFormDataContent formData) //{ // var client = GetHttpClient(); // var address = new Uri(String.Format(_baseUrl + "{0}", urlArguments)); // var response = await client.PostAsync(address, formData); // var data = await response.Content.ReadAsStringAsync(); // return JsonConvert.DeserializeObject<T>(data); //} public async Task <K> Post <T, K>(string urlArguments, T obj) { var client = GetHttpClient(); var content = new System.Net.Http.StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json"); var response = await client.PostAsync(String.Format(_baseUrl + "{0}", urlArguments), content); var data = await response.Content.ReadAsStringAsync(); return(JsonConvert.DeserializeObject <K>(data)); }
public void TodoController_Delete() { var jsonTask = JsonHelper.JsonSerialize <Task>(_taskOne); var content = new System.Net.Http.StringContent(jsonTask, Encoding.UTF8, "application/json"); var response = _server.HttpClient.DeleteAsync(string.Format("/todo/{0}", _taskOne.Id)).Result; var taskFound = _repository.GetById(_taskOne.Id); Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); Assert.IsNull(taskFound); }
public void terminate(int code, string des) { var term = new termination(); term.code = code; term.description = des; var content = new System.Net.Http.StringContent(term.toString(), Encoding.UTF8, "application/json"); content.Headers.Add("cookie", this.cookie.ToString()); client.PostAsync(launchUrl + "launch/" + launchToken + "/terminate", content); }
/// <summary> /// 插入 /// </summary> /// <typeparam name="T1">类型1</typeparam> /// <typeparam name="T2">类型2</typeparam> /// <param name="t">对象t</param> /// <returns>对象</returns> public T2 Insert <T1, T2>(T1 t) where T1 : class where T2 : class { string jsonValue = JsonConvert.SerializeObject(t); StringContent content = new System.Net.Http.StringContent(jsonValue, Encoding.UTF8, "application/json"); var response = HttpClient.PostAsync(URL, content).Result; var message = response.Content.ReadAsStringAsync().Result; var result = JsonConvert.DeserializeObject <T2>(message); return(result); }
public static async void Post(List <Package> packages) { var url = string.Format("{0}/{1}?ClientTime={2}", URL, AppStats.Current.AppInstance, DateTime.Now.ToString("s")); using (HttpClient client = new HttpClient()) { //#if DEBUG string sData = Newtonsoft.Json.JsonConvert.SerializeObject(packages); HttpContent content = new System.Net.Http.StringContent(sData, System.Text.Encoding.UTF8, "application/json"); var result = await client.PostAsync(url, content); } }
/// <summary> /// 更新 /// </summary> /// <typeparam name="T1"></typeparam> /// <typeparam name="T2"></typeparam> /// <param name="t"></param> /// <returns></returns> public T2 Update <T1, T2>(T1 t) where T1 : class where T2 : class { string jsonValue = JsonSerializer.SerializeToString <T1>(t); StringContent content = new System.Net.Http.StringContent(jsonValue, Encoding.UTF8, "application/json"); var response = HttpClient.PutAsync(URL, content).Result; var message = response.Content.ReadAsStringAsync().Result; var result = JsonSerializer.DeserializeFromString <T2>(message); return(result); }
public async Task <ProductosCantidadValorDTO> ProductosValorCarritoCliente(int clienteID) { decimal preciototal = 0; var query = (from x in contexto.Carrito where x.ClienteID == clienteID select x.ID).FirstOrDefault <int>(); var query2 = (from x in contexto.CarritoProducto where x.CarritoID == query select x.ProductoID).Distinct <int>().ToList(); List <ProductoEspecificoDto> productos = new List <ProductoEspecificoDto>(); ValorCarritoDTO valor = new ValorCarritoDTO() { productosID = query2 }; ProductosCantidadValorDTO objeto; string url = "https://localhost:44370/api/Producto/ProductosValorCarritoCliente"; using (var httpClient = new HttpClient()) { var json = Newtonsoft.Json.JsonConvert.SerializeObject(valor, Formatting.None); var data = new System.Net.Http.StringContent(json, Encoding.UTF8, "application/json"); var result = await httpClient.PostAsync(url, data); string resultado = result.Content.ReadAsStringAsync().Result; objeto = JsonConvert.DeserializeObject <ProductosCantidadValorDTO>(resultado); } foreach (ProductoEspecificoDto obj in objeto.productos) { int count = (from x in contexto.CarritoProducto where x.ProductoID == obj.ProductoID && x.CarritoID == query select x).Count(); ProductoEspecificoDto var = new ProductoEspecificoDto() { ProductoID = obj.ProductoID, Imagen = obj.Imagen, Descripcion = obj.Descripcion, Stock = obj.Stock, Nombre = obj.Nombre, Marca = obj.Marca, Cantidad = count, Categoria = obj.Categoria, Precio = obj.Precio }; productos.Add(var); preciototal += var.Precio * var.Cantidad; } objeto.productos = productos; objeto.valorcarrito = preciototal; return(objeto); }
public async Task <string> login(string server, string user, string passw) { client = new System.Net.Http.HttpClient(); client.DefaultRequestHeaders.Add("Accept", "application/json"); client.DefaultRequestHeaders.Add("X-Authenticate-User", user); client.DefaultRequestHeaders.Add("X-Authenticate-Password", passw); StringContent content = new System.Net.Http.StringContent("{\"Id\": \"" + user + "\", \"Password\": \"" + passw + "\",\"IsAdmin\": true}", Encoding.UTF8, "text/json"); HttpResponseMessage response = await client.PostAsync("https://" + server + "/login/", content); login_cred result = JsonConvert.DeserializeObject <login_cred>(await response.Content.ReadAsStringAsync()); return(result.AuthenticateToken); }
public void sendPost() { // Définition des variables qui seront envoyés HttpContent stringContent1 = new StringContent(param1String); // Le contenu du paramètre P1 HttpContent stringContent2 = new StringContent(param2String); // Le contenu du paramètre P2 HttpContent fileStreamContent = new StreamContent(paramFileStream); //HttpContent bytesContent = new ByteArrayContent(paramFileBytes); using (var client = new HttpClient()) using (var formData = new MultipartFormDataContent()) { formData.Add(stringContent1, "P1"); // Le paramètre P1 aura la valeur contenue dans param1String formData.Add(stringContent2, "P2"); // Le parmaètre P2 aura la valeur contenue dans param2String formData.Add(fileStreamContent, "FICHIER", "RETURN.xml"); // formData.Add(bytesContent, "file2", "file2"); try { var response = client.PostAsync(actionUrl, formData).Result; MessageBox.Show(response.ToString()); if (!response.IsSuccessStatusCode) { MessageBox.Show("Erreur de réponse"); } } catch (Exception Error) { MessageBox.Show(Error.Message); } finally { client.CancelPendingRequests(); } } }