C # HttpClient or HttpWebRequest class
I am currently using the HttpWebRequest class in my projects to call any 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;
}
It works :) But I'm curious how to do this. Does the HttpClient class have any disadvantages (your experience, opinions)?
Is using this class currently as the best way to invoke rest services (get, post, put, delete) instead of doing everything manually?
source to share
The advantage HttpClient
is that it is simpler and supported for most portable class library profiles. The downside is that it does not support requests other than http, which WebRequest
it does. In other words, it HttpClient
is a replacement for HttpWebRequest
, but there is no replacement for afaik FtpWebRequest
, etc.
Also see this post for more details: HttpClient vs HttpWebRequest
source to share