C# HttpClient 或 HttpWebRequest class
C# HttpClient or HttpWebRequest class
目前在我的项目中,我使用 HttpWebRequest class 来调用任何类型的 REST API。
像这样
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;
}
这是有效的:)
但我很好奇这样做的新方法。
HttpClient class 有任何缺点吗(您的经验、意见)?
目前 class 正在使用 'better' 调用休息服务(get、post、put、delete)的方式,而不是手动完成所有操作吗?
HttpClient
的优点是它更简单,并且受大多数便携式 Class 库配置文件支持。缺点是它不支持非 http 请求,而 WebRequest
支持。换句话说,HttpClient
是 HttpWebRequest
的替代品,但没有 FtpWebRequest
的替代品,等等
另请参阅此 post 了解更多详情:
目前在我的项目中,我使用 HttpWebRequest class 来调用任何类型的 REST API。
像这样
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;
}
这是有效的:) 但我很好奇这样做的新方法。 HttpClient class 有任何缺点吗(您的经验、意见)?
目前 class 正在使用 'better' 调用休息服务(get、post、put、delete)的方式,而不是手动完成所有操作吗?
HttpClient
的优点是它更简单,并且受大多数便携式 Class 库配置文件支持。缺点是它不支持非 http 请求,而 WebRequest
支持。换句话说,HttpClient
是 HttpWebRequest
的替代品,但没有 FtpWebRequest
的替代品,等等
另请参阅此 post 了解更多详情: