发布网友 发布时间: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;
}