Reputation: 1667
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 ?
Upvotes: 3
Views: 523
Reputation: 4811
The advantage of HttpClient
is that it is simpler, and supported on most Portable Class Library profiles. The disadvantage is that it doesn't support non-http requests, which WebRequest
does. In other words HttpClient
is a replacement for HttpWebRequest
but there isn't afaik a replacement for FtpWebRequest
, etc.
Also see this post for more details: HttpClient vs HttpWebRequest
Upvotes: 2