.net之访问Internet(上)
来源:互联网 发布:淘宝天猫京东的相同 编辑:程序博客网 时间:2024/06/08 06:01
.net提供了使用各种网络协议访问网络和Internet的类库
1. WebClient类
如果只是想从某个网站上读取文件,使用WebClient类就足够了,它通过一两个简单的命令就可以执行一些基本操作。使用起来非常简单,创建一个WinForm工程,添加ListBox控件,将百度页面的内容读取出来。WebClient类还有UploadFile和UploadData方法可以上传文件
代码示例:
public Form1()
{
InitializeComponent();
System.Net.WebClient Client = new WebClient();//创建client
Stream strm = Client.OpenRead("http://www.baidu.com");//创建读取流
StreamReader sr = new StreamReader(strm);
string line;
while ((line = sr.ReadLine()) != null)
{
listBox1.Items.Add(line);
}
strm.Close();//关闭流
}
2. WebRequest类和WebResponse类
WebClient类使用起来很简单,但是不能使用它提供身份验证证书,在使用它上传文件时,好多网站不接收没有身份验证的上传文件。而且WebClient可以使用任意协议接收和发送请求,这样它就不能处理类似于HTTP的cookie信息。如果想使用这些特性,就要使用WebRequest类和WebResponse类。
获取HTTP标题信息示例:
WebRequest wrq = WebRequest.Create("http://www.baidu.com");
HttpWebRequest hwrq = (HttpWebRequest)wrq;
listBox1.Items.Add("Request Timeout (ms) = " + wrq.Timeout);
listBox1.Items.Add("Request Keep Alive = " + hwrq.KeepAlive);
listBox1.Items.Add("Request AllowAutoRedirect = " + hwrq.AllowAutoRedirect);
listBox1.Items.Add("\r\n");
WebResponse wrs = wrq.GetResponse();
WebHeaderCollection whc = wrs.Headers;
for(int i = 0; i< whc.Count; i++)
{
listBox1.Items.Add("Header " + whc.GetKey(i) + " : " + whc[i]);
}
使用身份验证:在GetResponse之前给wrq的Credentials附上值,如下,
NetworkCredential myCred = new NetworkCredential("myusername", "mypassword");
wrq.Credentials = myCred;
异步页面请求:
public Form1()
{
InitializeComponent();
WebRequest wrq = WebRequest.Create("http://www.baidu.com");
wrq.BeginGetResponse(new AsyncCallback(OnResponse), wrq);//异步启动请求,OnResponse方法实际响应请求
}
protected void OnResponse(IAsyncResult ar)
{
WebRequest wrq = (WebRequest)ar.AsyncState;
WebResponse wrs = wrq.EndGetResponse(ar);
//to do read
}
3. 把输出结果显示成为HTML页面,神奇WebBrowser类
WebBrowser类可以让用户在窗体中导航网页,里面有众多IE所具有的属性可以用,还可以通过 Document 属性操作网页的内容
WebBrowser.Navigate(“访问地址”),就可以加载到需要访问的网页,它还支持前进后退等各种操作
- .net之访问Internet(上)
- .net之访问Internet(下)
- 使用.NET访问 Internet(1)
- 使用.NET访问 Internet(2)
- 使用.NET访问 Internet(3)
- 使用.NET访问Internet(4)
- 使用.NET访问Internet(5)
- 使用.NET访问 Internet(1)
- 使用.NET访问Internet(4)
- 使用.NET访问Internet(5) Paul_Ni(原作)(补充)
- 使用.NET访问Internet(5) Paul_Ni(原作)
- 使用.NET访问Internet(4) Paul_Ni(原作)(补充)
- 使用.NET访问 Internet(3) Paul_Ni(原作)
- 使用.NET访问Internet(4) Paul_Ni(原作)
- 使用.NET访问 Internet(2) Paul_Ni(原作)
- 使用.NET访问 Internet(1) Paul_Ni(原作)
- 透过防火墙访问internet上的sde server
- 在Internet上使用域名访问站点的方法
- ASCII 码值表
- Android 中的WiFi学习笔记(转载)
- 提防PQMAGIC和GHOST的误操作
- Android OpenGL ES 开发教程(16):Viewing和Modeling(MODELVIEW) 变换
- windows hadoop HDFS Failed to set permissions of path
- .net之访问Internet(上)
- POJ1000
- 电压跟随器
- 电脑蓝屏死机代码集合
- git cherry-pick和git rebase的混合用法
- CKEditor简介--笔记
- 单例设计模式
- Android新浪微博OAuth授权认证
- 单区域对焦 AF