Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /// <summary>POST request with body of "x-www-form-urlencoded" type to the api that responses in JSON</summary>
- /// <param name="url">String with url for POST request</param>
- /// <param name="postRequestBody">Body of POST request that will be serialized to "application/x-www-form-urlencoded" media type</param>
- /// <returns>Object of given generic type with response data</returns>
- public static T PostAsUrlEncodedWithJsonResponse<T>(string url, IEnumerable<KeyValuePair<string, string>> postRequestBody)
- {
- using (var client = new HttpClient())
- {
- client.DefaultRequestHeaders.Accept.Clear();
- client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
- HttpResponseMessage response = client.PostAsync(url, new FormUrlEncodedContent(postRequestBody)).Result;
- if (response.IsSuccessStatusCode)
- {
- response.Content.Headers.ContentType.MediaType = "application/json";
- return response.Content.ReadAsAsync<T>().Result;
- }
- else
- throw new HttpRequestException(string.Format("Error in {0} with params url: {1} and body: {2} ", MethodBase.GetCurrentMethod().Name, url, postRequestBody.ToString()));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement