Last active
October 25, 2020 13:06
-
-
Save Chibuikekenneth/a74664c3a62246329d082ec39b81231d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /// <summary> | |
| /// Post for a REST api | |
| /// </summary> | |
| /// <param name="token">authorization token</param> | |
| /// <param name="url">REST url for the resource</param> | |
| /// <param name="content">content</param> | |
| /// <returns>response from the rest url</returns> | |
| public async Task<JObject> PostAsync(string token, string url, string content) | |
| { | |
| byte[] data = Encoding.UTF8.GetBytes(content); | |
| WebRequest request = WebRequest.Create(url); | |
| request.Method = "POST"; | |
| request.ContentType = "application/json"; | |
| request.Headers.Add("Authorization", "Bearer " + token); | |
| request.ContentLength = data.Length; | |
| using (Stream stream = request.GetRequestStream()) | |
| { | |
| stream.Write(data, 0, data.Length); | |
| } | |
| try | |
| { | |
| WebResponse response = await request.GetResponseAsync(); | |
| using (StreamReader reader = new StreamReader(response.GetResponseStream())) | |
| { | |
| string responseContent = reader.ReadToEnd(); | |
| JObject adResponse = | |
| Newtonsoft.Json.JsonConvert.DeserializeObject<JObject>(responseContent); | |
| return adResponse; | |
| } | |
| } | |
| catch (WebException webException) | |
| { | |
| if (webException.Response != null) | |
| { | |
| using (StreamReader reader = new StreamReader(webException.Response.GetResponseStream())) | |
| { | |
| string responseContent = reader.ReadToEnd(); | |
| return Newtonsoft.Json.JsonConvert.DeserializeObject<JObject>(responseContent); ; | |
| } | |
| } | |
| } | |
| return null; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment