(48)C#网络4 web
WebClient 类
提供用于将数据发送到和接收来自通过 URI 确认的资源数据的常用方法
private delegate string delegatehWeb(); private void button1_Click(object sender, EventArgs e) { delegatehWeb delWeb ; AsyncCallback Callback = new AsyncCallback(webLoad); //delWeb.BeginInvoke(,); Task<string> x = webLoad(); //textBox1.Text = "abc"; //textBox1.Text = x.Result; //while (!string(x.Result)) { } } public async Task<string> webLoad() { HttpWebRequest httpWebRequest = WebRequest.CreateHttp("http://www.google.com/"); WebResponse httpWebResponse = await httpWebRequest.GetResponseAsync(); Stream stream = httpWebResponse.GetResponseStream(); Encoding encode = Encoding.GetEncoding("utf-8"); StreamReader readStream = new StreamReader(stream, encode); int count = readStream.Read(); string htmlStr = readStream.ReadToEnd(); return htmlStr; }
WebRequest 类
对统一资源标识符 (URI) 发出请求。 这是一个 abstract 类
WebResponse 类
提供来自统一资源标识符 (URI) 的响应。 这是一个 abstract 类。
HttpWebResponse 类
属性
ContentLength :当在子类中被重写时,获取或设置所发送的请求数据的内容长度。
Create(String):为指定的 URI 方案初始化新的 WebRequest 实例。
CreateHttp(String):为指定的 URI 字符串初始化新的 HttpWebRequest 实例。
HttpWebRequest httpWebRequest = WebRequest.CreateHttp("http://www.baidu.com");
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
Stream stream = httpWebResponse.GetResponseStream();
Encoding encode = Encoding.GetEncoding("utf-8");
StreamReader readStream = new StreamReader(stream, encode);
int count = readStream.Read();
string htmlStr = readStream.ReadToEnd();
textBox1.Text = htmlStr;