原文地址:http://www.cameronalbert.com/post/2008/03/HttpWebRequest-Helper-for-Silverlight-2.aspx
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using System.Windows.Browser;
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.Net;
namespace Lionsguard
{
public class HttpHelper
{
private HttpWebRequest Request { get; set; }
public Dictionary<string, string> PostValues { get; private set; }
public event HttpResponseCompleteEventHandler ResponseComplete;
private void OnResponseComplete(HttpResponseCompleteEventArgs e)
{
if (this.ResponseComplete != null)
{
this.ResponseComplete(e);
}
}
public HttpHelper(Uri requestUri, string method, params KeyValuePair<string, string>[] postValues)
{
this.Request = (HttpWebRequest)WebRequest.Create(requestUri);
this.Request.ContentType = "application/x-www-form-urlencoded";
this.Request.Method = method;
this.PostValues = new Dictionary<string, string>();
if (postValues != null && postValues.Length > 0)
{
foreach (var item in postValues)
{
this.PostValues.Add(item.Key, item.Value);
}
}
}
public void Execute()
{
this.Request.BeginGetRequestStream(new AsyncCallback(HttpHelper.BeginRequest), this);
}
private static void BeginRequest(IAsyncResult ar)
{
HttpHelper helper = ar.AsyncState as HttpHelper;
if (helper != null)
{
if (helper.PostValues.Count > 0)
{
using (StreamWriter writer = new StreamWriter(helper.Request.EndGetRequestStream(ar)))
{
foreach (var item in helper.PostValues)
{
writer.Write("{0}={1}&", item.Key, HttpUtility.UrlEncode(item.Value));
}
}
}
helper.Request.BeginGetResponse(new AsyncCallback(HttpHelper.BeginResponse), helper);
}
}
private static void BeginResponse(IAsyncResult ar)
{
HttpHelper helper = ar.AsyncState as HttpHelper;
if (helper != null)
{
HttpWebResponse response = (HttpWebResponse)helper.Request.EndGetResponse(ar);
if (response != null)
{
Stream stream = response.GetResponseStream();
if (stream != null)
{
using (StreamReader reader = new StreamReader(stream))
{
helper.OnResponseComplete(new HttpResponseCompleteEventArgs(reader.ReadToEnd()));
}
}
}
}
}
}
public delegate void HttpResponseCompleteEventHandler(HttpResponseCompleteEventArgs e);
public class HttpResponseCompleteEventArgs : EventArgs
{
public string Response { get; set; }
public HttpResponseCompleteEventArgs(string response)
{
this.Response = response;
}
}
}
使用方法
private void ProcessCommand(short cmd, string msg)
{
App app = App.Current as App;
HttpHelper helper = new HttpHelper(app.ServerUri, "POST",
new KeyValuePair<string, string>("authKey", app.AuthKey),
new KeyValuePair<string, string>("cmd", cmd.ToString()),
new KeyValuePair<string, string>("msg", msg));
helper.ResponseComplete += new HttpResponseCompleteEventHandler(this.CommandComplete);
helper.Execute();
}
private void CommandComplete(HttpResponseCompleteEventArgs e)
{
txtAlert.Text = e.Response;
}
如果您使用的是VBScript的话,工具类代码如下:
Public Class HttpHelper
Private Property Request() As HttpWebRequest
Get
Return _Request
End Get
Set(ByVal value As HttpWebRequest)
_Request = value
End Set
End Property
Private _Request As HttpWebRequest
Public Property PostValues() As Dictionary(Of String, String)
Get
Return _PostValues
End Get
Private Set(ByVal value As Dictionary(Of String, String))
_PostValues = value
End Set
End Property
Private _PostValues As Dictionary(Of String, String)
Public Event ResponseComplete As HttpResponseCompleteEventHandler
Private Sub OnResponseComplete(ByVal e As HttpResponseCompleteEventArgs)
RaiseEvent ResponseComplete(e)
End Sub
Public Sub New(ByVal requestUri As Uri, ByVal method As String, ByVal ParamArray postValues As KeyValuePair(Of String, String)())
Me.Request = DirectCast(WebRequest.Create(requestUri), HttpWebRequest)
Me.Request.ContentType = "application/x-www-form-urlencoded"
Me.Request.Method = method
Me.PostValues = New Dictionary(Of String, String)()
For Each item In postValues
Me.PostValues.Add(item.Key, item.Value)
Next
End Sub
Public Sub Execute()
Me.Request.BeginGetRequestStream(New AsyncCallback(AddressOf HttpHelper.BeginRequest), Me)
End Sub
Private Shared Sub BeginRequest(ByVal ar As IAsyncResult)
Dim helper As HttpHelper = TryCast(ar.AsyncState, HttpHelper)
If helper IsNot Nothing Then
Using writer As New StreamWriter(helper.Request.EndGetRequestStream(ar))
For Each item In helper.PostValues
writer.Write("{0}={1}&", item.Key, HttpUtility.UrlEncode(item.Value))
Next
End Using
helper.Request.BeginGetResponse(New AsyncCallback(AddressOf HttpHelper.BeginResponse), helper)
End If
End Sub
Private Shared Sub BeginResponse(ByVal ar As IAsyncResult)
Dim helper As HttpHelper = TryCast(ar.AsyncState, HttpHelper)
If helper IsNot Nothing Then
Dim response As HttpWebResponse = DirectCast(helper.Request.EndGetResponse(ar), HttpWebResponse)
If response IsNot Nothing Then
Dim stream As Stream = response.GetResponseStream()
If stream IsNot Nothing Then
Using reader As New StreamReader(stream)
helper.OnResponseComplete(New HttpResponseCompleteEventArgs(reader.ReadToEnd()))
End Using
End If
End If
End If
End Sub
End Class
Public Delegate Sub HttpResponseCompleteEventHandler(ByVal e As HttpResponseCompleteEventArgs)
Public Class HttpResponseCompleteEventArgs
Inherits EventArgs
Public Property Response() As String
Get
Return _Response
End Get
Set(ByVal value As String)
_Response = value
End Set
End Property
Private _Response As String
Public Sub New(ByVal response As String)
Me.Response = response
End Sub
End Class
在做自动更新程序时想省点事,直接使用HttpWebRequest和HttpWebResponse从服务器上下载更新的文件。 使用时注意Close响应流:
使用HttpWebRequest.GetResponse()取得HttpWebResponse接口后,必须要记得调用HttpWebResponse.close关闭流。
如果使用HttpWebResponse.GetResponseStream()取得响应流的话,那么使用此Stream的Close方法来关闭也是一样。
如果是使用StreamReader.ReadToEnd()从响应流中读取文本,则在读取完内容后会自动关闭流。
MSDN中这样描述HttpWebResponse.close方法:
Close 方法关闭响应流并释放到资源的连接以供其他请求重用。
您必须调用 Stream.Close 或 HttpWebResponse.Close 方法来关闭流并释放连接以供重用。不必同时调用 Stream.Close 和 HttpWebResponse.Close,但这样做不会导致错误。关闭该流失败会导致应用程序用尽连接。
连接限制好像是最大2个,不知是IIS的限制还是本地HttpWebRequest的限制。
分享到:
相关推荐
httpwebrequest工具类 可以有来抓取网面 代码从网上获取
silverlight HttpWebRequest post数据 到网站,并取得返回数据(c#) SilverlightHttpRequest---为Silverlight客户端 testwebSite---服务端
httpwebrequest 封装类
httpwebrequest调用webservice返回数据
httpwebrequest抓取页面小工具
HttpWebRequest详解HttpWebRequest详解HttpWebRequest详解
C# 多线程基本于httpwebrequest实现的下载功能 每个线程均可以通过事件追踪情况
1.这是一个用HttpWebRequest类构建完整Http多部请求上传文件的示例 2.上传地址是金山文档预览的地址,所以,只要上传的是word、pdf、excel一类的文档,可以通过返回的地址直接在线预览,是一种偷懒的文档在线浏览...
另一个好处是HttpWebRequest类不会阻塞UI线程。例如,当您从响应很慢的API服务器下载大文件时,您的应用程序的UI不会停止响应。HttpWebRequest通常和WebResponse一起使用,一个发送请求,一个获取数据。...
window phone WebClient和HttpWebRequest 并解决gb2312乱码问题
HttpWebRequest类的使用[文].pdf
C#中HttpWebRequest使用介绍 GET HTTP HTTPS 请求
.NET中封装静态类通过HttpWebRequest实现post、get、文件传输。
一个很实用的例子,注意要用OFFICE 2007
C#(也称Csharp)在多线程下并发执行HTTP请求的实现,采用C#封装HttpWebRequest类开发的多线程并发采集程序源码文档,文档中详细说明了HttpWebRequest并发HTTP请求实现网站采集的方法,经过测试同时并发1000+不是问题...
使用HttpWebRequest访问网页
本文将讲述如何采用HttpWebRequest方式每次读取固定大小数据片段(如4KB)发送至服务器,为大文件上传提供解决方案,本文还将详细讲述如何将“文件上传”功能做为用户自定义控件,实现模块重用。
本文将讲述如何采用HttpWebRequest方式每次读取固定大小数据片段(如4KB)发送至服务器,为大文件上传提供解决方案,本文还将详细讲述如何将“文件上传”功能做为用户自定义控件,实现模块重用。
silverlight实现在上传大附件功能,带进度条,httpWebRequest