public async Task <bool> UpdatePatientAsync(Patient patient) { string JSONresult = JsonConvert.SerializeObject(patient); //using (var client = new HttpClient()) //{ // client.DefaultRequestHeaders.Add("Accept", "application/fhir+json"); // client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/fhir+json; charset=utf-8"); // var a = new StringContent(JSONresult, Encoding.UTF8, "application/fhir+json"); // var response = await client.PutAsync(APIurl + patient.Id, // new StringContent(JSONresult, Encoding.UTF8, "application/fhir+json")).ConfigureAwait(false); // response.EnsureSuccessStatusCode(); // //return response.IsSuccessStatusCode; //} var client = new HttpClient(); client.DefaultRequestHeaders.Add("Accept", "application/fhir+json"); client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/fhir+json; charset=utf-8"); var httpResponse = await HttpClientExtensions.PutAsJsonAsync <Patient>(client, APIurl + patient.Id + "?_format=json", patient); var RequestBody = JsonConvert.SerializeObject(patient); var httpStatus = httpResponse.StatusCode; var UpdateResponse = await httpResponse.Content.ReadAsStringAsync(); return(true); }
private static HttpResponseMessage Put(Dictionary <string, string> resource, Dictionary <string, string> head, dynamic requesParams) { if (resource == null) { return(null); } if (string.IsNullOrEmpty(resource["BaseUrl"])) { throw new ArgumentNullException("baseUrl not is null!"); } string resourceUrl = resource["Value"]; if (string.IsNullOrEmpty(resourceUrl)) { throw new ArgumentNullException("resource not is null!"); } HttpResponseMessage response = null; if (requesParams != null && requesParams is IDictionary) { resourceUrl += GetParamsUrl(requesParams); } using (var client = new HttpClient()) { client.BaseAddress = new Uri(resource["BaseUrl"]); // Add an Accept header for JSON format. // 为JSON格式添加一个Accept报头 //注意这里的格式哦,为 "username:password" // mycache.Add(new Uri(url), "Basic", new NetworkCredential(username, password)); // myReq.Credentials = mycache; //client.DefaultRequestHeaders.Accept.Add( // new MediaTypeWithQualityHeaderValue("application/json")); if (head != null) { foreach (var key in head.Keys) { client.DefaultRequestHeaders.Add(key, head[key]); } } if (requesParams is string) { response = HttpClientExtensions.PutAsJsonAsync(client, resourceUrl, requesParams).Result; } else { MediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter(); // Use the JSON formatter to create the content of the request body. // 使用JSON格式化器创建请求体内容。 HttpContent content = new ObjectContent <string>(requesParams, jsonFormatter); response = client.PutAsync(resourceUrl, content).Result; } } return(response); }
/// <summary> /// Sends a PUT request for the specified path to put <see cref="IDictionary{String,Object}"/> content, as an asynchronous operation. /// </summary> /// <param name="relativePath">The path to the api.</param> /// <param name="data">The data to send.</param> /// <returns>A task object representing the asynchronous operation.</returns> /// <exception cref="ArgumentException">relativePath is not a valid relative URI.</exception> public async Task <CbClientResult <string> > HttpPutDictionaryAsync(string relativePath, IDictionary <string, object> data) { Uri path = this.EnsureRelativeUri(relativePath); HttpResponseMessage response = await HttpClientExtensions.PutAsJsonAsync(this.httpClient, path.ToString(), data); return(await this.TransformResponse(response, async (c) => { return await c.ReadAsStringAsync(); })); }
public async Task SingletonCRUD(string model, string singletonName) { string requestUri = string.Format(this.BaseAddress + "/{0}/{1}", model, singletonName); // Reset data source await ResetDataSource(model, singletonName); await ResetDataSource(model, "Partners"); // GET singleton HttpResponseMessage response = await this.Client.GetAsync(requestUri); dynamic result = JObject.Parse(await response.Content.ReadAsStringAsync()); // PUT singleton with {"ID":1,"Name":"singletonName","Revenue":2000,"Category":"IT"} result["Revenue"] = 2000; response = await HttpClientExtensions.PutAsJsonAsync(this.Client, requestUri, result); response.EnsureSuccessStatusCode(); // GET singleton/Revenue response = await this.Client.GetAsync(requestUri + "/Revenue"); result = JObject.Parse(await response.Content.ReadAsStringAsync()); Assert.Equal(2000, (int)result["value"]); // PATCH singleton with {"@odata.type":"#Microsoft.Test.E2E.AspNet.OData.Singleton.Company","Revenue":3000} HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("PATCH"), requestUri); request.Content = new StringContent(string.Format(@"{{""@odata.type"":""#{0}"",""Revenue"":3000}}", typeof(Company))); request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); response = await Client.SendAsync(request); response.EnsureSuccessStatusCode(); // GET singleton response = await this.Client.GetAsync(requestUri); result = JObject.Parse(await response.Content.ReadAsStringAsync()); Assert.Equal(3000, (int)result["Revenue"]); // Negative: Add singleton // POST singleton var company = new Company(); response = await this.Client.PostAsJsonAsync(requestUri, company); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); // Negative: Delete singleton // DELETE singleton response = await this.Client.DeleteAsync(requestUri); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); }
private static async Task <dynamic> Request <T>(AllowedHttpVerbs method, string url, dynamic parameters) { if (string.IsNullOrWhiteSpace(_developerKey)) { throw new NoDeveloperKeyException(); } using (HttpClient client = new HttpClient()) { client.BaseAddress = new Uri(_apiBaseUri); client.DefaultRequestHeaders.Add("X-BetaSeries-Key", _developerKey); client.DefaultRequestHeaders.Add("X-BetaSeries-Version", _apiVersion); //add usertoken if (_userToken != null) { client.DefaultRequestHeaders.Add("Authorization", $"Bearer {_userToken}"); } //request HttpResponseMessage result = null; switch (method) { case AllowedHttpVerbs.Delete: result = await client.DeleteAsync($"{url}"); break; case AllowedHttpVerbs.Get: result = await client.GetAsync($"{url}"); break; case AllowedHttpVerbs.Post: result = await HttpClientExtensions.PostAsJsonAsync(client, url, parameters); break; case AllowedHttpVerbs.Put: result = await HttpClientExtensions.PutAsJsonAsync(client, url, parameters); break; } using (result) { string resultAsString = await result.Content.ReadAsStringAsync(); if (result.IsSuccessStatusCode) { return(JsonConvert.DeserializeObject(resultAsString)); } else { ErrorResponse errorResponse = JsonConvert.DeserializeObject <ErrorResponse>(resultAsString); if (errorResponse != null) { throw new BetaSeriesException(errorResponse); } return(errorResponse); } } } }
public async Task EntitySetNavigationLinkCRUD(string model, string format) { string requestUri = string.Format(this.BaseAddress + "/{0}/Partners(1)/Company", model); string navigationUri = requestUri + "/$ref"; string formatQuery = string.Format("?$format={0}", format); //Reset data source await ResetDataSource(model, "MonstersInc"); await ResetDataSource(model, "Partners"); // PUT Partners(1)/Company/$ref string idLinkBase = string.Format(this.BaseAddress + "/{0}/MonstersInc", model); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, navigationUri); request.Content = new StringContent("{ \"@odata.id\" : \"" + idLinkBase + "\"}"); request.Content.Headers.ContentType = MediaTypeWithQualityHeaderValue.Parse("application/json"); var response = await Client.SendAsync(request); Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); // GET Partners(1)/Company response = await this.Client.GetAsync(requestUri); var result = JObject.Parse(await response.Content.ReadAsStringAsync()); Assert.Equal("MonstersInc", (string)result["Name"]); // PUT Partners(1)/Company result["Revenue"] = 2000; response = await HttpClientExtensions.PutAsJsonAsync(this.Client, requestUri, result); response.EnsureSuccessStatusCode(); // GET Partners(1)/Company/Revenue response = await this.Client.GetAsync(requestUri + formatQuery); result = JObject.Parse(await response.Content.ReadAsStringAsync()); Assert.Equal(2000, (int)result["Revenue"]); // PATCH Partners(1)/Company request = new HttpRequestMessage(new HttpMethod("PATCH"), requestUri); request.Content = new StringContent(string.Format(@"{{""@odata.type"":""#{0}"",""Revenue"":3000}}", typeof(Company))); request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); response = await Client.SendAsync(request); response.EnsureSuccessStatusCode(); // GET Partners(1)/Company/Revenue response = await this.Client.GetAsync(requestUri + formatQuery); result = JObject.Parse(await response.Content.ReadAsStringAsync()); Assert.Equal(3000, (int)result["Revenue"]); // DELETE Partners(1)/Company/$ref response = await Client.DeleteAsync(navigationUri); Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); // GET Partners(1)/Company response = await this.Client.GetAsync(requestUri + formatQuery); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); // Negative: POST Partners(1)/Company var company = new Company(); response = await this.Client.PostAsJsonAsync(requestUri, company); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); }