Advertisement
DenisBabarykin

Untitled

Oct 19th, 2016
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.21 KB | None | 0 0
  1. /// <summary>POST request with body of "x-www-form-urlencoded" type to the api that responses in JSON</summary>
  2. /// <param name="url">String with url for POST request</param>
  3. /// <param name="postRequestBody">Body of POST request that will be serialized to "application/x-www-form-urlencoded" media type</param>
  4. /// <returns>Object of given generic type with response data</returns>
  5. public static T PostAsUrlEncodedWithJsonResponse<T>(string url, IEnumerable<KeyValuePair<string, string>> postRequestBody)
  6. {
  7.     using (var client = new HttpClient())
  8.     {
  9.         client.DefaultRequestHeaders.Accept.Clear();
  10.         client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  11.  
  12.         HttpResponseMessage response = client.PostAsync(url, new FormUrlEncodedContent(postRequestBody)).Result;
  13.         if (response.IsSuccessStatusCode)
  14.         {
  15.             response.Content.Headers.ContentType.MediaType = "application/json";
  16.             return response.Content.ReadAsAsync<T>().Result;
  17.         }
  18.         else
  19.             throw new HttpRequestException(string.Format("Error in {0} with params url: {1} and body: {2} ", MethodBase.GetCurrentMethod().Name, url, postRequestBody.ToString()));
  20.     }
  21. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement