silverlight向服务器post数据类

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;


public class HttpClient
{
    
private WebRequest webRequest = null;
    
public delegate void ResponseEventHandler(String responseResult);
    
public event ResponseEventHandler onResponseEventHandler;
    
public delegate void RequestEventHandler();
    
public event RequestEventHandler onRequestEventHandler;
    
public string PostData { getset; }

    
public HttpClient(Uri clientUri)
    {
        Uri endpoint 
= clientUri;
        webRequest 
= WebRequest.Create(endpoint);
        webRequest.ContentType 
= "application/x-www-form-urlencoded";
        webRequest.Method 
= "POST";
    }

    
public void Post()
    {
        webRequest.BeginGetRequestStream(
new AsyncCallback(RequestReady), webRequest);
    }
    
private void RequestReady(IAsyncResult asyncResult)
    {
        
if (this.onRequestEventHandler != null)
        {
            
this.onRequestEventHandler();
        }
        WebRequest request 
= asyncResult.AsyncState as WebRequest;
        Stream requestStream 
= request.EndGetRequestStream(asyncResult);

        
using (StreamWriter writer = new StreamWriter(requestStream))
        {
            writer.Write(
this.PostData);
            writer.Flush();
            writer.Close();
        }
        webRequest.BeginGetResponse(
new AsyncCallback(ResponseReady), webRequest);
    }
    
private void ResponseReady(IAsyncResult asyncResult)
    {
        
if (this.onResponseEventHandler != null)
        {
            WebRequest request 
= asyncResult.AsyncState as WebRequest;
            WebResponse response 
= request.EndGetResponse(asyncResult);

            
using (Stream responseStream = response.GetResponseStream())
            {
                String responseResult 
= String.Empty;
                
try
                {
                    StreamReader reader 
= new StreamReader(responseStream);
                    responseResult 
= reader.ReadToEnd();
                }
                
catch (WebException er)
                {
                    responseResult 
= er.Message;
                }
                
catch (Exception er)
                {
                    responseResult 
= er.Message;
                }
                
this.onResponseEventHandler(responseResult);
            }
        }
    }
}

作者:nasa
出处:nasa.cnblogs.com
联系:nasa_wz@hotmail.com
QQ:12446006
posted @ 2008-08-10 20:42  王喆(nasa)  阅读(1466)  评论(0编辑  收藏  举报