您的位置:首页 > 理论基础 > 计算机网络

网络和通信 - Silverlight 中的 HTTP 通信和安全

2011-03-20 11:13 232 查看
Silverlight 支持几种使用 HTTP/HTTPS 的方案。虽然可以使用多种方式和技术执行 HTTP 调用,但是下表描述的是针对这些 HTTP
通信方案的建议方法

View Code

SynchronizationContext syncContext;
private void Button_Click(object sender, RoutedEventArgs e)
{
// Grab SynchronizationContext while on UI Thread
syncContext = SynchronizationContext.Current;

// Create request
HttpWebRequest request =
WebRequest.Create(new Uri("http://blogs.contoso.com/post-create?blogID=1234",
UriKind.Absolute))
as HttpWebRequest;
request.Method = "POST";

// Make async call for request stream.  Callback will be called on a background thread.
IAsyncResult asyncResult =
request.BeginGetRequestStream(new AsyncCallback(RequestStreamCallback), request);

}
string statusString;
private void RequestStreamCallback(IAsyncResult ar)
{
HttpWebRequest request = ar.AsyncState as HttpWebRequest;
request.ContentType = "application/atom+xml";
Stream requestStream = request.EndGetRequestStream(ar);
StreamWriter streamWriter = new StreamWriter(requestStream);

streamWriter.Write("<entry xmlns='http://www.w3.org/2005/Atom'>"
+ "<title type='text'>New Restaurant</title>"
+ "<content type='xhtml'>"
+ "  <div xmlns='http://www.w3.org/1999/xhtml'>"
+ "   <p>There is a new Thai restaurant in town!</p>"
+ "   <p>I ate there last night and it was <b>fabulous</b>.</p>"
+ "   <p>Make sure and check it out!</p>"
+ "  </div>"
+ " </content>"
+ "<author>"
+ "   <name>Pilar Ackerman</name>"
+ "  <email>packerman@contoso.com</email>"
+ " </author>"
+ "</entry>");

// Close the stream.
streamWriter.Close();

// Make async call for response.  Callback will be called on a background thread.
request.BeginGetResponse(new AsyncCallback(ResponseCallback), request);

}
private void ResponseCallback(IAsyncResult ar)
{
HttpWebRequest request = ar.AsyncState as HttpWebRequest;
WebResponse response = null;
try
{
response = request.EndGetResponse(ar);
}
catch (WebException we)
{
statusString = we.Status.ToString();
}
catch (SecurityException se)
{
statusString = se.Message;
if (statusString == "")
statusString = se.InnerException.Message;
}

// Invoke onto UI thread
syncContext.Post(ExtractResponse, response);
}

private void ExtractResponse(object state)
{
HttpWebResponse response = state as HttpWebResponse;

if (response != null && response.StatusCode == HttpStatusCode.OK)
{
StreamReader responseReader = new StreamReader(response.GetResponseStream());

tb1.Text = response.StatusCode.ToString() +
" Response: "  + responseReader.ReadToEnd();
}
else
tb1.Text = "Post failed: " + statusString;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: