Created
July 16, 2019 10:14
-
-
Save johnmmoss/ba50f6ede24cc7020f111fa5687c8671 to your computer and use it in GitHub Desktop.
Methods using HttpClient for Integration style testing
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
public (HttpStatusCode Status, string Content) Get(string url) | |
{ | |
HttpResponseMessage response; | |
string content = string.Empty; | |
using (var client = new HttpClient()) | |
{ | |
response = client.GetAsync(url).Result; | |
} | |
if (response != null) | |
{ | |
content = response.Content.ReadAsStringAsync().Result; | |
} | |
return (response.StatusCode, content); | |
} | |
public (HttpStatusCode status, dynamic responseContent) PostXml(string url, string xml) | |
{ | |
dynamic responseContent = null; | |
HttpResponseMessage response = null; | |
var httpContent = new StringContent(xml, Encoding.UTF8, "application/xml"); | |
using (var client = new HttpClient()) | |
{ | |
response = client.PostAsync(url, httpContent).Result; | |
} | |
if (response != null) | |
{ | |
var content = response.Content.ReadAsStringAsync().Result; | |
responseContent = XElement.Load(content); | |
} | |
return (response.StatusCode, responseContent); | |
} | |
public (HttpStatusCode status, dynamic responseContent) PostJson(string url, object json) | |
{ | |
dynamic responseContent = null; | |
HttpResponseMessage response = null; | |
var requestContentJson = JsonConvert.SerializeObject(json); | |
var requestContentBytes = Encoding.UTF8.GetBytes(requestContentJson); | |
var requestPostContent = new ByteArrayContent(requestContentBytes); | |
requestPostContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); | |
using (var client = new HttpClient()) | |
{ | |
response = client.PostAsync(url, requestPostContent).Result; | |
} | |
if (response != null) | |
{ | |
var content = response.Content.ReadAsStringAsync().Result; | |
responseContent = JsonConvert.DeserializeObject(content); | |
} | |
return (response.StatusCode, responseContent); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment