2012-11-02 55 views
0

我有需要將數據傳遞給Web服務(SMS)一個網頁,我試圖用WebRequest做這項工作,但是當我使用這個類出現以下錯誤:HttpWebRequest的參數傳遞給WebService的

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

是一個.net/WDSL web服務?它可能會更容易創建Web引用或服務引用,並讓它處理http交互。至於你的方法,你是否在寫入後嘗試刷新流? –

+0

@FrankThomas謝謝你的回覆不,它不是.net web服務 –

+0

在PHP中的web服務網站? –

回答

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); 
} 
+0

謝謝@索尼我會試試看,並告訴你 –

+0

,但我將如何將參數添加到strNewValues? –

+0

我可以在strNewValues上使用string.format並添加值,然後在byteArray []中使用字符串 –