zoukankan      html  css  js  c++  java
  • WP7>网络>读取网页源码

    问题:如何读取一个网页的源码

      我的理解:其实很简单,只需要用“WebClient”类即可

    示例:

    读取百度首页源码,然后放到messgaebox中show出来

    前置条件:

    1)  C#基础

    2)  XAML基础

    实现:

    目录:

    1)  创建一个基本应用

    2)  添加一个按钮

    3)  添加事件代码

    4)  测试运行

    1 创建一个基本应用

    1)  创建一个基本的Windows Phone应用程序,OS版本7.0

    2)  清除多余的界面元素(留下一个基本的Grid控件)

    1 <Grid x:Name="LayoutRoot" Background="Transparent">
    2 
    3 </Grid>

    2 添加一个按钮

    1     <Grid x:Name="LayoutRoot" Background="Transparent">
    2         <Button Content="Do" Height="72" HorizontalAlignment="Left" Margin="157,169,0,0" Name="button1" VerticalAlignment="Top" Width="160" Click="button1_Click" />
    3     </Grid>

    3 添加事件代码

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Net;
     5 using System.Windows;
     6 using System.Windows.Controls;
     7 using System.Windows.Documents;
     8 using System.Windows.Input;
     9 using System.Windows.Media;
    10 using System.Windows.Media.Animation;
    11 using System.Windows.Shapes;
    12 using Microsoft.Phone.Controls;
    13 using System.IO;
    14 
    15 namespace PhoneApp1
    16 {
    17     public partial class MainPage : PhoneApplicationPage
    18     {
    19         // 构造函数
    20         public MainPage()
    21         {
    22             InitializeComponent();
    23             
    24         }
    25 
    26         private void button1_Click(object sender, RoutedEventArgs e)
    27         {
    28             WebClient webClient = new WebClient();
    29             webClient.OpenReadAsync(new Uri("http://www.baidu.com"));
    30             webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
    31         }
    32 
    33         void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
    34         {
    35             using (StreamReader reader = new StreamReader(e.Result))
    36             {
    37                 MessageBox.Show(reader.ReadToEnd());
    38             }
    39         }
    40     }
    41 }

    4 测试运行

     说明:

      1)  使用OpenReadAsync方法设置需要读取的页面,其本意是“开启指定资源的数据流”

      2)  设置OpenReadCompleted事件,并在事件中读取结果

  • 相关阅读:
    中国剩余定理(CRT) & 扩展中国剩余定理(ExCRT)总结
    各种求逆元
    A*(A_star)搜索总结
    线段树总结
    C++的STL
    Unable to make the session state request to the session state server处理方法
    判断UserAgent是否来自微信
    VS2010 EntityFramework Database First
    VS2010类似Eclipse文件查找功能-定位到
    Newtonsoft.Json随手记
  • 原文地址:https://www.cnblogs.com/cation/p/2751515.html
Copyright © 2011-2022 走看看