public async Task<Result> DeleteData(Uri uri, StringContent json, UserAuthenticationEntity userAuthenticationEntity, string language = "ja") { using (var httpClient = new HttpClient()) { try { var authenticationManager = new AuthenticationManager(); Result result = new Result(false, ""); if (RefreshTime(userAuthenticationEntity.ExpiresInDate)) { var tokens = await authenticationManager.RefreshAccessToken(userAuthenticationEntity.RefreshToken); result.Tokens = tokens.Tokens; } httpClient.DefaultRequestHeaders.Add("Accept-Language", language); httpClient.DefaultRequestHeaders.Add("Origin", "http://psapp.dl.playstation.net"); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", userAuthenticationEntity.AccessToken); var response = await httpClient.DeleteAsync(uri); var responseContent = await response.Content.ReadAsStringAsync(); result.IsSuccess = response.IsSuccessStatusCode; result.ResultJson = responseContent; return result; } catch (Exception) { return new Result(false, string.Empty); } } }
/* * [HttpPost] * [ValidateAntiForgeryToken] * public ActionResult Edit([Bind(Include = "bill_id,total_price,state,payment_type,date_of_bill,command_reference")] bill bill) * { * //bill.state = true; * if (ModelState.IsValid) * { * httpClient.BaseAddress = new Uri("http://localhost:8081/ConsomiTounsi/"); * httpClient.DefaultRequestHeaders.Accept.Clear(); * httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); * * var postTask = httpClient.PutAsJsonAsync<bill>("updateBill?id=" + 1 , bill); * postTask.Wait(); * * var result = postTask.Result; * if (result.IsSuccessStatusCode) * { * return RedirectToAction("Index"); * } * } * return View(bill); * } */ // GET: Bills/Delete/5 public ActionResult Delete(long bill_id) { var tokenResponse = httpClient.DeleteAsync(baseAddress + "deletebillById/" + bill_id).Result; if (tokenResponse.IsSuccessStatusCode) { return(RedirectToAction("Index")); } else { return(View(new bill())); } }
/// <summary> /// Runs an HttpClient issuing a POST request against the controller. /// </summary> static async void RunClient() { var handler = new HttpClientHandler(); handler.Credentials = new NetworkCredential("Boris", "xyzxyz"); var client = new System.Net.Http.HttpClient(handler); var bizMsgDTO = new BizMsgDTO { Name = "Boris", Date = DateTime.Now, User = "******", }; // *** POST/CREATE BizMsg Uri address = new Uri(_baseAddress, "/api/BizMsgService"); HttpResponseMessage response = await client.PostAsJsonAsync(address.ToString(), bizMsgDTO); // Check that response was successful or throw exception // response.EnsureSuccessStatusCode(); // BizMsg result = await response.Content.ReadAsAsync<BizMsg>(); // Console.WriteLine("Result: Name: {0}, Date: {1}, User: {2}, Id: {3}", result.Name, result.Date.ToString(), result.User, result.Id); Console.WriteLine(response.StatusCode + " - " + response.Headers.Location); // *** PUT/UPDATE BizMsg var testID = response.Headers.Location.AbsolutePath.Split('/')[3]; bizMsgDTO.Name = "Boris Momtchev"; response = await client.PutAsJsonAsync(address.ToString() + "/" + testID, bizMsgDTO); Console.WriteLine(response.StatusCode); // *** DELETE BizMsg response = await client.DeleteAsync(address.ToString() + "/" + testID); Console.WriteLine(response.StatusCode); }
static void Main(string[] args) { Uri baseAddress = new Uri("http://*****:*****@gmail.com", PhoneNo = "789" }; Console.WriteLine("\n添加联系人003"); httpClient.PutAsync<Contact>("/api/contacts", contact, new JsonMediaTypeFormatter()).Wait(); contacts = httpClient.GetAsync("/api/contacts").Result.Content.ReadAsAsync<IEnumerable<Contact>>().Result; ListContacts(contacts); contact = new Contact { Id = "003", Name = "王五", EmailAddress = "*****@*****.**", PhoneNo = "987" }; Console.WriteLine("\n修改联系人003"); httpClient.PostAsync<Contact>("/api/contacts", contact, new XmlMediaTypeFormatter()).Wait(); contacts = httpClient.GetAsync("/api/contacts").Result.Content.ReadAsAsync<IEnumerable<Contact>>().Result; ListContacts(contacts); Console.WriteLine("\n删除联系人003"); httpClient.DeleteAsync("/api/contacts/003").Wait(); contacts = httpClient.GetAsync("/api/contacts").Result.Content.ReadAsAsync<IEnumerable<Contact>>().Result; ListContacts(contacts); Console.Read(); }
public async Task <JObject> GetJsonAsync() { Debug.WriteLine(uri); using (var client = new System.Net.Http.HttpClient()) { string jsonString = ""; client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); if (type == RequestType.GET) { jsonString = await client.GetStringAsync(uri); Debug.WriteLine(jsonString); } else if (type == RequestType.POST) { CreateJsonContent(); System.Net.Http.HttpResponseMessage response = await client.PostAsync(uri, new StringContent(obj.ToString(), Encoding.UTF8, "application/json")); Debug.WriteLine("response : " + response.ToString()); jsonString = await response.Content.ReadAsStringAsync(); Debug.WriteLine(jsonString); } else if (type == RequestType.DELETE) { System.Net.Http.HttpResponseMessage response = await client.DeleteAsync(uri); Debug.WriteLine("response : " + response.StatusCode.ToString()); jsonString = await response.Content.ReadAsStringAsync(); } Debug.WriteLine("jsonstring : " + jsonString); return(JObject.Parse(jsonString)); } }
public async Task<HttpResponseMessage> GetResponseAsync(RestCommand command, string data = "") { try { using (var handler = new HttpClientHandler()) { if (_credentials != null) handler.Credentials = _credentials; using (var httpClient = new HttpClient(handler)) { ConfigureHttpClient(httpClient); switch (command.HttpMethod) { case HttpMethod.Get: return await httpClient.GetAsync(command.FullResourceUri); case HttpMethod.Put: return await httpClient.PutAsync(command.FullResourceUri, new StringContent(data)); case HttpMethod.Post: return await httpClient.PostAsync(command.FullResourceUri, new StringContent(data)); case HttpMethod.Delete: return await httpClient.DeleteAsync(command.FullResourceUri); } throw new Exception(string.Format("The command '{0}' does not have a valid HttpMethod. (Type: {1})", command, command.GetType().FullName)); } } } catch (Exception e) { throw new Exception("An error occured while performing the request.", e); } }
private async Task <bool> DeleteProductsSuppliersAsync(int supplierID) { HttpClient client = new System.Net.Http.HttpClient(); // Get all ProductsSuppliers from API List <ProductsSuppliers> prodSuppsFull; var response = await client.GetAsync("https://localhost:44327/api/ProductsSuppliersAPI"); prodSuppsFull = JsonConvert.DeserializeObject <List <ProductsSuppliers> >(await response.Content.ReadAsStringAsync()); // Filter List to include only those with supplierId var prodSuppsFiltered = prodSuppsFull.FindAll(ps => ps.SupplierId == supplierID); // for each ProductsSuppliers object in list, delete from database var codes = new List <HttpStatusCode>(); foreach (var item in prodSuppsFiltered) { var responseFromProdSupps = await client.DeleteAsync($"https://localhost:44327/api/ProductsSuppliersAPI/{item.ProductSupplierId}"); codes.Add(responseFromProdSupps.StatusCode); } bool success = true; foreach (var code in codes) { if (code != HttpStatusCode.Accepted && code == HttpStatusCode.OK && code == HttpStatusCode.NoContent) { success = false; } } return(success); }
public async Task <HttpResponseMessage> DeleteAsync(string resourceUrl, Dictionary <string, string> headers = null) { AddHeadersToRequest(headers); var result = await _httpClient.DeleteAsync(resourceUrl); return(result); }
private void CallWebService(string baseUrl, string authenticationUrl, string taskUrl, string application, string userName, string password) { var cookieContainer = new CookieContainer(); using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer }) using (var httpClient = new HttpClient(handler)) { httpClient.BaseAddress = new Uri(baseUrl); httpClient.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); var result = httpClient.PostAsJsonAsync(authenticationUrl, new { Application=application, UserName = userName, Password = password }).Result; result = httpClient.DeleteAsync(taskUrl).Result; result.EnsureSuccessStatusCode(); //var userProfile = await result.Content.ReadAsAsync<UserProfile>(); //if (userProfile == null) // throw new UnauthorizedAccessException(); //return userProfile; } }
/// <summary> /// DELETE api/Heroes/{id} /// </summary> public async Task DeleteAsync(long id) { var requestUri = new Uri(this.baseUri, "api/Heroes/" + id); var responseMessage = await client.DeleteAsync(requestUri); responseMessage.EnsureSuccessStatusCode(); }
/// <summary> Send a DELETE request to the specified Uri as an asynchronous operation.</summary> /// <param name="uri"> The uri we are sending our delete request. </param> /// <param name="token"> The token used by the API to authorize and identify. </param> /// <returns> The <see cref="Task" />. </returns> public async Task DeleteAsync(Uri uri, CancellationToken cancellationToken, string token = "") { using (System.Net.Http.HttpClient httpClient = CreateHttpClient(token)) { await httpClient.DeleteAsync(uri).ConfigureAwait(false); } }
public void inline_call_to_invalidate_using_expression_tree_with_custom_action_name_is_correct() { var client = new HttpClient(_server); var result = client.DeleteAsync(_url + "Delete_non_standard_name").Result; _cache.Verify(s => s.RemoveStartsWith(It.Is<string>(x => x == "inlineinvalidate-getbyid")), Times.Exactly(1)); }
private static async Task AlbumsControllerTest(HttpClient client) { // create album await client.PostAsync("Albums/Create", new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("title", "album 009") })); await client.PostAsync("Albums/Create", new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("title", "album 010") })); // get all albums Console.WriteLine(await client.GetStringAsync("Albums/All")); // update album await client.PutAsync("Albums/Update", new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("id", "2"), new KeyValuePair<string, string>("year", "2014"), new KeyValuePair<string, string>("producer", "gosho ot pochivka") })); // delete album await client.DeleteAsync("Albums/Delete/1"); // add song to album await client.PutAsync("Albums/AddSong?albumId=2&songId=2", null); // add artist to album await client.PutAsync("Albums/AddArtist?albumId=2&artistId=2", null); }
private static void DeleteHotel(string serverUrl, int deleteHotelNo) { Console.WriteLine("Exercise6"); Console.WriteLine(" 6) Delete(HTTP Delete) the Hotel number 200"); using (var client = new HttpClient()) { client.BaseAddress = new Uri(serverUrl); client.DefaultRequestHeaders.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); try { string deleteUrl = "api/hotels/" + deleteHotelNo; var response = client.DeleteAsync(deleteUrl).Result; Console.WriteLine("Delete Async " + deleteUrl); Console.WriteLine(response.StatusCode); if (response.IsSuccessStatusCode) { Console.WriteLine("Succcesfull delete"); } else { Console.WriteLine("Someting went wrong, hotel not deleted"); } } catch (Exception) { throw; } } }
public async Task <T> Delete <T>(string url) { try { var response = await Client.DeleteAsync(url); if ((int)response.StatusCode >= 200 && (int)response.StatusCode <= 299) { var serializedData = await response.Content.ReadAsStringAsync(); return(JsonConvert.DeserializeObject <T>(serializedData)); } else if ((int)response.StatusCode == 400) { throw new BadRequestException(response.ReasonPhrase); } else if ((int)response.StatusCode == 404) { throw new BadRequestException(response.ReasonPhrase); } else { throw new Exception(response.ReasonPhrase); } } catch (HttpRequestException e) { throw e; } }
internal static async Task <HttpStatusCode> DeleteScheduled(int transferId) { HttpResponseMessage response = await httpClient.DeleteAsync( "api/schedule/" + transferId); return(response.StatusCode); }
public async Task <TEntity> DeleteAsync <TEntity>(string url, CancellationToken?token = null) where TEntity : class, new() { var response = await Client.DeleteAsync(url, token ?? CancellationToken.None).ConfigureAwait(false); response = Validate(response); return(await ContentToEntity <TEntity>(response).ConfigureAwait(false)); }
private async void DeleteAnEvent() { try { using (var client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", String.Format("Bearer {0}", this.parent.Bearer)); using (var response = await client.DeleteAsync(this.DELETE_EVENT.ToString() + "/" + this.numericId.Value)) { if (response.IsSuccessStatusCode) { MessageBox.Show("The event was deleted."); } else { MessageBox.Show(response.ReasonPhrase, "Error"); } } } } catch (Exception ex) { MessageBox.Show(ex.Message, "Error"); } }
private HttpResponseMessage DeleteSync() { string result = string.Empty; try { var httpResponseMessage = _httpClient.DeleteAsync(_addressSuffix).Result; if (httpResponseMessage.StatusCode == HttpStatusCode.NotFound) { throw new ExcecaoAcessoApi(); } if (httpResponseMessage.StatusCode == HttpStatusCode.OK) { return(httpResponseMessage); } result = httpResponseMessage.Content.ReadAsStringAsync().Result; var jsonErrorDataResponse = JsonConvert.DeserializeObject <JsonErrorDataResponse>(result); throw new ExcecaoRestful(jsonErrorDataResponse, httpResponseMessage.StatusCode); } catch (ExcecaoRestful) { throw; } catch (Exception) { throw new Exception(result); } }
/// <summary> /// Http DELETE请求方式 删除数据 /// </summary> /// <param name="url"></param> /// <param name="content"></param> /// <returns></returns> public ResponseResult <T> HttpDelete <T>(string url, WebHeaderCollection webHeaders = null, ResponseResultType resultType = ResponseResultType.ResultInfo) { try { //设置全局定义的个性化安全认证 SetDefaultHeaders(_httpItem.SecurityHeaders); //加载或者更新私定的安全认证 SetDefaultHeaders(webHeaders); //var postDate = JsonConvert.SerializeObject(""); //var httpContent = new StringContent(postDate, Encoding.UTF8); //httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json") { CharSet = "utf-8" }; var postResult = _client.DeleteAsync(url); //处理数据解析 return(JsonConvertResultData <T>(postResult, resultType)); } catch (InvalidOperationException ex) { return(new ResponseResult <T>() { Code = (int)HttpStatusCode.BadRequest, Msg = ex.StackTrace }); } catch (Exception ex) { return(new ResponseResult <T>() { Code = (int)HttpStatusCode.BadRequest, Msg = ex.StackTrace }); } }
public string DeleteGroup(string id, UserData userData) { try { client = new HttpClient(); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Add("Timestamp", userData.Timestamp.ToString()); client.DefaultRequestHeaders.Add("Digest", userData.AuthenticationHash); client.DefaultRequestHeaders.Add("Public-Key", userData.PublicKey); client.DeleteAsync("http://localhost:3000/contact/" + id) .ContinueWith(deleteTask => { deleteTask.Result.EnsureSuccessStatusCode(); var result = deleteTask.Result.Content.ReadAsStringAsync(); client.Dispose(); return result; }); } catch (Exception ex) { throw ex; } return null; }
public void inline_call_to_invalidate_using_expression_tree_with_param_is_correct() { var client = new HttpClient(_server); var result = client.DeleteAsync(_url + "Delete_parameterized").Result; _cache.Verify(s => s.RemoveStartsWith(It.Is<string>(x => x == "webapi.outputcache.v2.tests.testcontrollers.inlineinvalidatecontroller-get_c100_s100_with_param")), Times.Exactly(1)); }
public async Task<JObject> GetJsonAsync() { Debug.WriteLine(uri); using (var client = new System.Net.Http.HttpClient()) { string jsonString = ""; client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); if (type == RequestType.GET) { jsonString = await client.GetStringAsync(uri); Debug.WriteLine(jsonString); } else if (type == RequestType.POST) { CreateJsonContent(); System.Net.Http.HttpResponseMessage response = await client.PostAsync(uri, new StringContent(obj.ToString(), Encoding.UTF8, "application/json")); Debug.WriteLine("response : " + response.ToString()); jsonString = await response.Content.ReadAsStringAsync(); Debug.WriteLine(jsonString); } else if (type == RequestType.DELETE) { System.Net.Http.HttpResponseMessage response = await client.DeleteAsync(uri); Debug.WriteLine("response : " + response.StatusCode.ToString()); jsonString = await response.Content.ReadAsStringAsync(); } Debug.WriteLine("jsonstring : " + jsonString); return JObject.Parse(jsonString); } }
public void DeleteTest() { Task.Run(async () => { using (var client = new HttpClient()) { // add childnode first var values = new Dictionary<string, string> { { "uuid", childNode.selfNode.uuid}, { "toxid", childNode.selfNode.toxid}, }; long timeStamp = Skynet.Utils.Utils.UnixTimeNow(); client.DefaultRequestHeaders.Add("Skynet-Time", timeStamp + ""); var response = await client.PostAsync(baseUrl + "node/" + testNode.selfNode.uuid + "/childNodes", new FormUrlEncodedContent(values)); string responseString = await response.Content.ReadAsStringAsync(); var deleteResponse = await client.DeleteAsync(baseUrl + "node/" + testNode.selfNode.uuid + "/childNodes/" + childNode.selfNode.uuid); string deleteResponseString = await deleteResponse.Content.ReadAsStringAsync(); NodeResponse res = JsonConvert.DeserializeObject<NodeResponse>(deleteResponseString); Assert.AreEqual(res.statusCode, NodeResponseCode.OK); Assert.AreEqual(timeStamp, res.time); Assert.AreEqual(timeStamp, testNode.childNodesModifiedTime); } }).GetAwaiter().GetResult(); }
public static async Task<string> ReceiveAndDeleteMessage() { if (_token == null) _token = GetSasToken(); HttpResponseMessage response = null; try { var httpClient = new HttpClient(); var fullAddress = BaseAddress + QueueName + "/messages/head" + "?timeout=3600000"; httpClient.DefaultRequestHeaders.Add("Authorization", _token); response = await httpClient.DeleteAsync(fullAddress); return await response.Content.ReadAsStringAsync(); } catch (Exception) { if (response == null || response.StatusCode != HttpStatusCode.Unauthorized) return null; _token = GetSasToken(); return await ReceiveAndDeleteMessage(); } }
public ActionResult Delete(FormCollection collection) { //try //{ // Promotion promo = db.Promotion.Find(Int32.Parse(collection["id"])); // db.Promotion.Remove(promo); // db.SaveChanges(); // return Json(new { status = "success", message = "Promotion removed" }); //} //catch //{ // return Json(new { status = "error", message = "Something went wrong. Unable to delete promo." }); //} int id = Int32.Parse(collection["id"]); client.BaseAddress = new Uri(url); var deleteTask = client.DeleteAsync(string.Format("promo/{0}", id)); deleteTask.Wait(); var result = deleteTask.Result; if (result.IsSuccessStatusCode) { return(Json(new { status = "success", message = "Promotion removed" })); } return(Content("Something went wrong!")); }
public void FakeServer_CapturesAllRequests() { using (var fakeServer = new FakeServer()) { fakeServer.Start(); var baseAddress = fakeServer.BaseUri; Action<Action, int> repeat = (a, times) => { for (var i = 0; i < times; i++) a(); }; var url1 = "/request1"; var url2 = "/request2"; var url3 = "/request3"; var url4 = "/request4"; var httpClient = new HttpClient(); httpClient.DeleteAsync(new Uri(baseAddress + url1)).Wait(); repeat(() => httpClient.GetAsync(new Uri(baseAddress + url2)).Wait(), 2); repeat(() => httpClient.PostAsync(new Uri(baseAddress + url3), new StringContent(url3)).Wait(), 3); repeat(() => httpClient.PutAsync(new Uri(baseAddress + url4), new StringContent(url4)).Wait(), 4); fakeServer.CapturedRequests.Count(x => x.Method == Http.Delete && x.Url == url1).Should().Be(1); fakeServer.CapturedRequests.Count(x => x.Method == Http.Get && x.Url == url2).Should().Be(2); fakeServer.CapturedRequests.Count(x => x.Method == Http.Post && x.Url == url3 && x.Body == url3).Should().Be(3); fakeServer.CapturedRequests.Count(x => x.Method == Http.Put && x.Url == url4 && x.Body == url4).Should().Be(4); } }
/// <summary> /// Delete data via HTTP /// </summary> /// <param name="url">The URL to post data to</param> /// <returns>The response message</returns> public static async Task<HttpResponseMessage> Delete(string url) { var handler = new HttpClientHandler(); var client = new HttpClient(handler, true); var responseMessage = await client.DeleteAsync(url); return responseMessage; }
public async void DeleteAsync(string url) { var uri = new Uri(url); System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient(); System.Net.Http.HttpResponseMessage response = await httpClient.DeleteAsync(uri); }
//Methods that are related with the resetData process public ActionResult resetData() { var client = new HttpClient(); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var response = client.DeleteAsync("http://localhost:2012/api/Tournament/resetTournament").Result; return View("topView"); }
public void Delete <T>(int id = 0) where T : class { using (var client = new NetHttpClient()) { client.SetDefaultHeaders(); client.DeleteAsync(string.Concat(_apiUrl.TrimEnd('/'), "/", id)).Start(); } }
public async Task<HttpResponseMessage> Delete(string controller, string identificator) { using (var client = new HttpClient()) { client.BaseAddress = new Uri(_baseAddress); return await client.DeleteAsync("api/" + controller + "/" + identificator + "/"); } }
public void Remove(Order ord) { using (var client = new HttpClient()) { HttpResponseMessage response = client.DeleteAsync(ServerAddress.Address + "order/" + ord.Id).Result; } }
//Delete existing model in database public void deleteModel() { HttpClient client = new HttpClient(); client.BaseAddress = new Uri(RestServerData.URL); HttpResponseMessage response; response = client.DeleteAsync("delete/reservation/?id=" + rsvr_rID).Result; }
public async Task<bool> DeleteTaskModelAsync(TaskModel taskModel) { var httpClient = new HttpClient(); var response = await httpClient.DeleteAsync(WebServiceUrl + taskModel.Id); return response.IsSuccessStatusCode; }
public void Remove(Customer cus) { using (var client = new HttpClient()) { HttpResponseMessage response = client.DeleteAsync(ServerAddress.Address + "customer/" + cus.Id).Result; } }
//Delete existing model in database public void deleteModel() { HttpClient client = new HttpClient(); client.BaseAddress = new Uri(RestServerData.URL); HttpResponseMessage response; response = client.DeleteAsync("delete/maintenance/?id=" + mtr_ID).Result; }
public static HttpResponseMessage SendDeleteRequest(string baseUrl,List<Parameter> parameters) { string url = baseUrl; url += "?" + Helpers.EncodedParamString(parameters); HttpClient client = new HttpClient(); return client.DeleteAsync(url).Result; }
//DELETE public async Task<String> DeleteTaskAsync(string path) { var parser = new Parser(GraphUri, path, null, _accessToken); var httpClient = new HttpClient(); var response = await httpClient.DeleteAsync(parser.Url); return await response.Content.ReadAsStringAsync(); }
public PictureDto Delete(int id) { using (var client = new HttpClient()) { HttpResponseMessage response = client.DeleteAsync("http://localhost:9372/api/PictureApi" + id).Result; return response.Content.ReadAsAsync<PictureDto>().Result; } }
public void Delete(int ID) { using (var client = new HttpClient()) { HttpResponseMessage response = client.DeleteAsync("http://localhost:54980/api/products/" + ID).Result; } }
public async Task <JsonDefaultResponse <T> > Delete <T>(string endpoint) { HttpResponseMessage message = await client.DeleteAsync(endpoint); string response = message.Content.ReadAsStringAsync().Result; return(JsonTransformer.Deserialize <JsonDefaultResponse <T> >(response)); }
/// <summary> /// DELETE-запрос /// </summary> /// <param name="client">HttpCLient</param> /// <param name="requestUri">Адрес назначения</param> /// <param name="query"></param> /// <returns></returns> public static async Task DeleteVoidAsync(this System.Net.Http.HttpClient client, string requestUri, object query = null) { using (client) { await client.DeleteAsync(requestUri.AddQuery(query)); } }
/// <summary> /// Envía una petición a la url especificada con las opciones /// de configuración requerida /// </summary> /// <typeparam name="T">Tipo de dato a esperado</typeparam> /// <param name="Url">Url destino</param> /// <param name="Method">Tipo de método de la petición</param> /// <param name="Data">Objeto a enviar en la petición</param> /// <param name="TimeOut">Tiempo de espera en minutos</param> /// <returns></returns> public static T Request <T>(string Url, HttpMethodEnum Method, object Data = null, string Token = null, int TimeOut = 10) { using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient()) { try { client.Timeout = TimeSpan.FromMinutes(TimeOut); client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("text/plain")); if (!string.IsNullOrEmpty(Token)) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token); } HttpResponseMessage response = null; switch (Method) { case HttpMethodEnum.Get: response = client.GetAsync(Url).Result; break; case HttpMethodEnum.PostJson: response = client.PostAsJsonAsync(Url, Data).Result; break; case HttpMethodEnum.PutJson: response = client.PutAsJsonAsync(Url, Data).Result; break; case HttpMethodEnum.Delete: response = client.DeleteAsync(Url).Result; break; default: break; } if (response.IsSuccessStatusCode) { T result = response.Content.ReadAsAsync <T>().Result; return(result); } else { return(default(T)); } } catch (Exception ex) { // Excepciones throw ex; } } }
/// <summary> /// Delete an issue. Only unit test issues can be deleted: other issues are silently left in place. /// </summary> /// <remarks> /// https://www.jetbrains.com/help/youtrack/standalone/operations-api-issues.html#delete-Issue-method /// </remarks> public bool DeleteIssue(string issueId) { if (!issueId.StartsWith("AUT-")) { return(false); } var response = _client.DeleteAsync($"https://{_youTrackBaseSite}/youtrack/api/issues/{issueId}").Result; return(response.IsSuccessStatusCode); }
private async Task <Suppliers> DeleteSupplierAsync(string path, int supplierID) { // Delete Suppliers Object in Delete Request HttpClient client = new System.Net.Http.HttpClient(); HttpResponseMessage response = await client.DeleteAsync(path + "/" + supplierID); var returnSupplier = JsonConvert.DeserializeObject <Suppliers>(await response.Content.ReadAsStringAsync()); return(returnSupplier); }
private async Task <Products> DeleteProductAsync(string path, int productID) { // Delete Product Object in Delete Request, path includes ProductsID HttpClient client = new System.Net.Http.HttpClient(); HttpResponseMessage response = await client.DeleteAsync(path + "/" + productID); var returnProduct = JsonConvert.DeserializeObject <Products>(await response.Content.ReadAsStringAsync()); return(returnProduct); }
public override async Task <T> DeleteAsync <T>(string path) { T dataResult = default(T); HttpResponseMessage response = await _client.DeleteAsync(path); if (response.IsSuccessStatusCode) { dataResult = await response.Content.ReadAsAsync <T>(); } return(dataResult); }
public static async Task <ResponseResult <TResult> > DeleteAsync <TResult>(this System.Net.Http.HttpClient client, string url) { using var response = await client.DeleteAsync(url); return(new ResponseResult <TResult> { Succeed = response.IsSuccessStatusCode, StatusCode = response.StatusCode, Headers = response.Headers, Result = await response.Content.ReadAsync <TResult>() }); }
public async void CierreSesion(string Authorization) { Uri requestUri = new Uri(URL + "/sesiones/" + Authorization); var objClint = new System.Net.Http.HttpClient(); objClint.DefaultRequestHeaders.Add("Authorization", Authorization); System.Net.Http.HttpResponseMessage respon = await objClint.DeleteAsync(requestUri).ConfigureAwait(continueOnCapturedContext: false); string responJsonText = await respon.Content.ReadAsStringAsync().ConfigureAwait(continueOnCapturedContext: false); //MessageBox.Show("Respuesta: " + respon.ReasonPhrase); }
public async Task <string> Delete(string url, int id) { var client = new System.Net.Http.HttpClient(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var response = await client.DeleteAsync(string.Format(ApiUrl, $"{url}/{id}")); var result = response.Content.ReadAsStringAsync().Result; return(result); }
private async Task <Packages> DeletePackageAsync(string path, int packageID) { // Instantiate HTTP Client HttpClient client = new System.Net.Http.HttpClient(); // make Delete Call to specific ID corresponding to Packages object passed in HttpResponseMessage response = await client.DeleteAsync(path + "/" + packageID); // collect return package and return var returnPackage = JsonConvert.DeserializeObject <Packages>(await response.Content.ReadAsStringAsync()); return(returnPackage); }
public async Task <HttpResponse> DeleteAsync(string requestURI, Dictionary <string, string> headers) { headers.ToList().ForEach(header => { _client.DefaultRequestHeaders.Remove(header.Key); _client.DefaultRequestHeaders.Add(header.Key, header.Value); }); var task = await _client.DeleteAsync(requestURI); return(new HttpResponse((int)task.StatusCode, null, task.ReasonPhrase)); }
/// <summary> /// Delete purchase order by ID /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors /// DeleteOrder store/order/{orderId} /// </summary> /// <param name="orderId">ID of the order that needs to be deleted</param> public async Task DeleteOrderAsync(string orderId) { var requestUri = "store/order/" + Uri.EscapeDataString(orderId); var responseMessage = await client.DeleteAsync(requestUri); try { responseMessage.EnsureSuccessStatusCode(); } finally { responseMessage.Dispose(); } }
/// <summary> /// Deletes a pet /// DeletePet pet/{petId} /// </summary> /// <param name="petId">Pet id to delete</param> public async Task DeletePetAsync(long petId) { var requestUri = "pet/" + petId; var responseMessage = await client.DeleteAsync(requestUri); try { responseMessage.EnsureSuccessStatusCode(); } finally { responseMessage.Dispose(); } }
/// <summary> /// Delete user /// This can only be done by the logged in user. /// DeleteUser user/{username} /// </summary> /// <param name="username">The name that needs to be deleted</param> public async Task DeleteUserAsync(string username) { var requestUri = "user/" + Uri.EscapeDataString(username); var responseMessage = await client.DeleteAsync(requestUri); try { responseMessage.EnsureSuccessStatusCode(); } finally { responseMessage.Dispose(); } }
/// <summary> /// ValuesDeleteById /api/Values/{id} /// </summary> /// <returns>Success</returns> public async Task ValuesDeleteByIdAsync(int id) { var requestUri = "/api/Values/" + id; var responseMessage = await client.DeleteAsync(requestUri); try { responseMessage.EnsureSuccessStatusCode(); } finally { responseMessage.Dispose(); } }
private async static void Process() { //获取当前联系人列表 HttpClient httpClient = new HttpClient(); HttpResponseMessage response = await httpClient.GetAsync("http://localhost/selfhost/tyz/api/products"); IEnumerable<Product> products = await response.Content.ReadAsAsync<IEnumerable<Product>>(); Console.WriteLine("当前联系人列表:"); ListContacts(products); //添加新的联系人 Product product = new Product { Name = "王五", PhoneNo = "0512-34567890", EmailAddress = "*****@*****.**" }; await httpClient.PostAsJsonAsync<Product>("http://localhost/selfhost/tyz/api/products", product); Console.WriteLine("添加新联系人“王五”:"); response = await httpClient.GetAsync("http://localhost/selfhost/tyz/api/products"); products = await response.Content.ReadAsAsync<IEnumerable<Product>>(); ListContacts(products); //修改现有的某个联系人 response = await httpClient.GetAsync("http://localhost/selfhost/tyz/api/products/001"); product = (await response.Content.ReadAsAsync<IEnumerable<Product>>()).First(); product.Name = "赵六"; product.EmailAddress = "*****@*****.**"; await httpClient.PutAsJsonAsync<Product>("http://localhost/selfhost/tyz/api/products/001", product); Console.WriteLine("修改联系人“001”信息:"); response = await httpClient.GetAsync("http://localhost/selfhost/tyz/api/products"); products = await response.Content.ReadAsAsync<IEnumerable<Product>>(); ListContacts(products); //删除现有的某个联系人 await httpClient.DeleteAsync("http://localhost/selfhost/tyz/api/products/002"); Console.WriteLine("删除联系人“002”:"); response = await httpClient.GetAsync("http://localhost/selfhost/tyz/api/products"); products = await response.Content.ReadAsAsync<IEnumerable<Product>>(); ListContacts(products); }
static void Main(string[] args) { System.Threading.Thread.Sleep(100); Console.Clear(); Console.WriteLine("**************************开始执行获取API***********************************"); HttpClient client = new HttpClient(); //Get All Product 获取所有 HttpResponseMessage responseGetAll = client.GetAsync(url + "api/Products").Result; string GetAllProducts = responseGetAll.Content.ReadAsStringAsync().Result; Console.WriteLine("GetAllProducts方法:" + GetAllProducts); //Get Product根据ID获取 HttpResponseMessage responseGetID = client.GetAsync(url + "api/Products/1").Result; string GetProduct = responseGetID.Content.ReadAsStringAsync().Result; Console.WriteLine("GetProduct方法:" + GetProduct); //Delete Product 根据ID删除 HttpResponseMessage responseDeleteID = client.DeleteAsync(url + "api/Products/1").Result; // string DeleteProduct = responseDeleteID.Content.ReadAsStringAsync().Result; Console.WriteLine("DeleteProduct方法:" ); //HttpContent abstract 类 //Post Product 添加Product对象 var model = new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }; HttpContent content = new ObjectContent(typeof(Product), model, new JsonMediaTypeFormatter()); client.PostAsync(url + "api/Products/", content); //Put Product 修改Product client.PutAsync(url + "api/Products/", content); Console.ReadKey(); }
private static async Task SongsControllerTest(HttpClient client) { // create songs await client.PostAsync("Songs/Create", new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("title", "qka pesen 007"), new KeyValuePair<string, string>("artistid", "2") })); await client.PostAsync("Songs/Create", new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("title", "qka pesen 008"), new KeyValuePair<string, string>("artistid", "2") })); // get all songs Console.WriteLine(await client.GetStringAsync("Songs/All")); // update song await client.PutAsync("Songs/Update", new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("id", "2"), new KeyValuePair<string, string>("year", "2010"), new KeyValuePair<string, string>("genre", "narodna pesen") })); // delete song await client.DeleteAsync("api/Songs/Delete/1"); }