我正在尝试使用此功能将数据发送到服务器:
public static async Task<Byte[]> sendData(Byte[] bt)
{
try
{
System.Net.HttpWebRequest myWebRequest = (HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
myWebRequest.Method = "POST";
myWebRequest.ContentType = "text/xml";
myWebRequest.AllowReadStreamBuffering = true;
using (var requestStream = (Stream)(await Task<Stream>.Factory.FromAsync(myWebRequest.BeginGetRequestStream, myWebRequest.EndGetRequestStream, myWebRequest)))
{
requestStream.Write(bt, 0, bt.Length);
}
using (var response = (HttpWebResponse)(await Task<WebResponse>.Factory.FromAsync(myWebRequest.BeginGetResponse, myWebRequest.EndGetResponse, myWebRequest)))
{
using (var responseStream = response.GetResponseStream())
{
bt = new byte[responseStream.Length];
responseStream.Read(bt, 0, bt.Length);
return bt;
}
}
}
catch (Exception ex)
{
return null;
}
}
我收到服务器的回复,说没有发送数据(ContentLength == 0)。实际上,如果我在流请求中写入后查看myWebRequest.ContentLength,则_ContentLength
设置为0,ContentLength
设置为-1。
我错过了什么吗?
感谢您的帮助!