首页 行业资讯 宠物日常 宠物养护 宠物健康 宠物故事

c#如何使用rest接口读写数据

发布网友 发布时间:2022-04-21 07:29

我来回答

1个回答

热心网友 时间:2023-11-07 04:46

string DoRequest(HttpWebRequest req, string data = null)
{
var responseData = string.Empty;
var start = DateTime.Now;
#if DEBUG
Trace.TraceInformation(req.Address.AbsoluteUri + "\t+Request With Data:" + data);
#endif
if (req.Method == WebRequestMethods.Http.Post)
req.ContentType = "text/plain; charset=" + Encoding.WebName;
Exception exception = null;
try
{
if (!string.IsNullOrEmpty(data))
{
byte[] bs = Encoding.GetBytes(data);
req.ContentLength = bs.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
}
}

using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding))
{
responseData = reader.ReadToEnd();
}
}

}
catch (Exception ex) { exception= ex; }
finally
{
req.Abort();
}

#if DEBUG
Trace.TraceInformation(req.Address.AbsoluteUri + "\t + Response:" + responseData);
#endif
var end = DateTime.Now;
if ((end - start).TotalSeconds > 10)
Trace.TraceWarning(req.Address.AbsoluteUri + "\t + 请求时间过长,耗时:" + (end - start).ToString());
if (exception != null) throw exception;
return responseData;
}

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com