使用情景如下:
UI線程中
{
HttpWebRequest wr =
(HttpWebRequest)WebRequest.Create("http://www.exzample.com/exzample.aspx");
wr.Method = "POST";
// 必須要指定ContentType,否則服務器有可能返回Page Not Found
wr.ContentType = "application/x-www-form-urlencoded";
wr.BeginGetRequestStream(new AsyncCallback(GetRequestStream_Completed), wr);
}
工作線程中
{
public void GetRequestStream_Completed(IAsyncResult ar)
{
HttpWebRequest wr = ar.AsyncState as HttpWebRequest;
Stream s = wr.EndGetRequestStream(ar);
s.Position = 0;
s.Write(new Byte[]{ 1, 2, 3 }, 0, 3); // 寫入需要的字節流
// 如果不調用此函數的話,下面的BeginGetResponse將拋出NotSupportException異常,
// 但是在桌面版的Silvalight沒有這個要求
s.Close();
wr.BeginGetResponse(new AsyncCallback(GetResponse_Completed), wr);
}
public void GetResponse_Completed(IAsyncResult ar)
{
HttpWebRequest wr = ar.AsyncState as HttpWebRequest;
Stream s = wr.EndGetResponse(ar);
s.Position = 0;
Byte[] buffer = new Byte[s.Length];
s.Read(buffer, 0, s.Length);
s.Close();
}
}