使用system.net中常用class来取得web 资源(webClient....)
引自:http://book.csdn.net/bookfiles/452/10045215961.shtml
<1>发送带有认证信息的HTTP请求并取回响应 (WebRequest/WebResponse)
string uri = " http://server/path/WebForm.aspx";
WebRequest wreq = WebRequest.Create(uri);
string uid = "someDomainUserID";
string pwd = "theDomainPassword";
string domain = "theDomainName";
NetworkCredential nc = new NetworkCredential(uid, pwd, domain);
wreq.Credentials = nc;
Console.WriteLine("Sending authenticated request to " + uri);
WebResponse wres = wreq.GetResponse();
Stream st = wres.GetResponseStream();
StreamReader sr = new StreamReader(st);
string res = sr.ReadToEnd();
sr.Close();
st.Close();
Console.WriteLine("HTTP Response is ");
Console.WriteLine(res);
注解
如果需要发送一个带有网络认证证书(用户ID、域,以及密码)的HTTP请求 ,则可以使用WebRequest和WebResponse类。这些类位于System.Web命名空间,缺省情况下这个命名空间对于控制台程序来说是不可访问的,所以必须要添加一个关于System.Web.dll文件的工程引用。请注意,WebRequest对象不是利用new关键字通过构造函数来创建的,而是利用工厂机制(factory mechanism)通过Create()方法来创建的。创建NetworkCredential对象之后,可以把这个对象与WebRequest对象相关联。接下来调用WebRequest.GetResponse()方法返回的是一个WebResponse对象;你可能预计需要显式地调用一个“Send”方法,实际上不需要。HTTP响应的数据流(stream),和其他数据流一样,可以被绑定到一个StreamReader对象上,然后你就可以通过ReadToEnd()方法把整个HTTP响应作为一个字符串取回。
如果需要发送一个带有网络认证证书(用户ID、域,以及密码)的HTTP请求 ,则可以使用WebRequest和WebResponse类。这些类位于System.Web命名空间,缺省情况下这个命名空间对于控制台程序来说是不可访问的,所以必须要添加一个关于System.Web.dll文件的工程引用。请注意,WebRequest对象不是利用new关键字通过构造函数来创建的,而是利用工厂机制(factory mechanism)通过Create()方法来创建的。创建NetworkCredential对象之后,可以把这个对象与WebRequest对象相关联。接下来调用WebRequest.GetResponse()方法返回的是一个WebResponse对象;你可能预计需要显式地调用一个“Send”方法,实际上不需要。HTTP响应的数据流(stream),和其他数据流一样,可以被绑定到一个StreamReader对象上,然后你就可以通过ReadToEnd()方法把整个HTTP响应作为一个字符串取回。
WebRequest和WebResponse类实际上都是抽象基类(abstract base classes)。在实际工作中,WebRequest-WebResponse更适合用来处理相对较为简单的带认证信息的HTTP请求。如果认证信息不是必需的,那么使用WebClient类要更好一些。如果你需要发送一个HTTP POST请求,那么HttpWebRequest和HttpWebResponse类通常是更好的选择。WebRequest和WebResponse类支持异步调用,但是对于轻量级的自动化程序来说,通常也用不到。本节的这些代码可以用来检查一个ASP.NET程序的响应,但是要将这部分代码扩展成一个自动化测试程序,则需要根据给定的期望值来检查HTTP响应,
<2> 获取不能得到contentlength的response
/**/
/// <summary>
/// Reads the huge stream in chunks , one chunk at a time and returns the
/// bytes array.
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
private byte [] ReadResponseInChunks(WebResponse response)
... {
BinaryReader reader
= new BinaryReader(
response.GetResponseStream());
// huge memory buffer (512k), we don't know final size!
MemoryStream memoryStream
= new MemoryStream(
0x080000);
int readLen = 0;
byte[] chunk = new byte[
0x000400];
byte[] bufferedData = null;
// read from stream until EOF
while ((readLen = reader.Read(chunk, 0, chunk.Length)) > 0)
...{
// write to memory stream
memoryStream.Write(chunk, 0, readLen);
}
// get final data
bufferedData = memoryStream.ToArray();
// clean up
memoryStream.Dispose();
return bufferedData;
}
/// Reads the huge stream in chunks , one chunk at a time and returns the
/// bytes array.
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
private byte [] ReadResponseInChunks(WebResponse response)
... {
BinaryReader reader
= new BinaryReader(
response.GetResponseStream());
// huge memory buffer (512k), we don't know final size!
MemoryStream memoryStream
= new MemoryStream(
0x080000);
int readLen = 0;
byte[] chunk = new byte[
0x000400];
byte[] bufferedData = null;
// read from stream until EOF
while ((readLen = reader.Read(chunk, 0, chunk.Length)) > 0)
...{
// write to memory stream
memoryStream.Write(chunk, 0, readLen);
}
// get final data
bufferedData = memoryStream.ToArray();
// clean up
memoryStream.Dispose();
return bufferedData;
}
<3>WebClient上传
WebClient webClient
=
new
WebClient();
webClient.Headers.Add( " Content-Type " , ContentType);
try
... ... {
responseBytes = webClient.UploadData(uploadUrl, bytes);
return true;
}
catch (WebException ex)
... ... {
Stream resp = ex.Response.GetResponseStream();
responseBytes = new byte[ex.Response.ContentLength];
resp.Read(responseBytes, 0, responseBytes.Length);
}
return false ;
webClient.Headers.Add( " Content-Type " , ContentType);
try
... ... {
responseBytes = webClient.UploadData(uploadUrl, bytes);
return true;
}
catch (WebException ex)
... ... {
Stream resp = ex.Response.GetResponseStream();
responseBytes = new byte[ex.Response.ContentLength];
resp.Read(responseBytes, 0, responseBytes.Length);
}
return false ;
<4>WebClient下载
引自:http://dotnet.aspx.cc/ShowDetail.aspx?id=0A6660CE-4138-41EF-B882-15DB65564709
PageUrl = UrlText.Text;
WebClient wc = new WebClient();
wc.Credentials = CredentialCache.DefaultCredentials;
/**/ ///方法一:
Byte[] pageData = wc.DownloadData(PageUrl);
ContentHtml.Text = Encoding.Default.GetString(pageData);
/**/ /// 方法二:
/// ***************代码开始**********
/// Stream resStream = wc.OpenRead(PageUrl);
/// StreamReader sr = new StreamReader(resStream,System.Text.Encoding.Default);
/// ContentHtml.Text = sr.ReadToEnd();
/// resStream.Close();
/// **************代码结束********
///
wc.Dispose();
Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1751862