我有一个需要将数据传递到Web服务(SMS)的网页,我尝试使用WebRequest
来完成这项工作但是当我使用这个类时出现以下错误:
Cannot close stream until all bytes are written
在此行之后的行中:
stOut.WriteLine(strNewValue,number,text);
有什么问题?我尝试使用Flush()
,但无法使用
public class SendSms
{
public SendSms(string number, string text)
{
string strNewValue;
string strResponse;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://www.buymessage.com/ostazSms/send.php");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
strNewValue = "usr=****&pwd=*****&to={0}&msg={1}";
req.ContentLength = strNewValue.Length;
using(StreamWriter stOut = new StreamWriter (req.GetRequestStream(), System.Text.Encoding.Unicode))
{
stOut.WriteLine(strNewValue,number,text);
}
StreamReader stIn = new StreamReader(req.GetResponse().GetResponseStream());
strResponse = stIn.ReadToEnd();
stIn.Close();
}
}
答案 0 :(得分:1)
您的问题是您致电WriteLine
,这可能不会发送所有数据。
以下是对帖子数据进行编码并将其全部发送的代码段:
string strNewValue = string.Format("usr=****&pwd=*****&to={0}&msg={1}", "A", "B");
byte[] byteArray = Encoding.UTF8.GetBytes (strNewValue);
req.ContentLength = byteArray.Length;
using (Stream dataStream = req.GetRequestStream ()) {
dataStream.Write (byteArray, 0, byteArray.Length);
}