currently in my projects I use the HttpWebRequest class to call any kind of REST APIs.
like this
public string Post(string postData)
{
string resultString = string.Empty;
WebRequest req = WebRequest.Create(_serviceEndoint);
HttpWebRequest httpWebReq = (HttpWebRequest)req;
httpWebReq.CookieContainer = _cookieContainer;
req.ContentType = "application/xml";
req.Method = "POST";
req.Credentials = new NetworkCredential("Administrator", "Password");
try
{
Stream requestStream = req.GetRequestStream();
UTF8Encoding encoding = new UTF8Encoding();
byte[] bytes = encoding.GetBytes(postData);
requestStream.Write(bytes, 0, bytes.Length);
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
if (resp.StatusCode == HttpStatusCode.OK)
{
using (Stream respStream = resp.GetResponseStream())
{
StreamReader reader = new StreamReader(respStream, Encoding.UTF8);
resultString = reader.ReadToEnd();
}
}
}
catch (Exception ex)
{
resultString = ex.ToString();
}
return resultString;
}
This is working :) But I am curious about the rather new way of doing so. Does the HttpClient class have any downsides (your experiences, opinions)?
Is using that class currently the 'better' way to call rest services (get,post, put, delete), instead of doing all the things manually ?