简体   繁体   中英

C# html code reader error in WPF

I have a problem when trying to get html code from http://mp3.zing.vn (no problem with other sites), the code I received like this . Please help me to solve this problem.

MainWindow.xaml

<Window x:Class="test.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:test"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <local:ViewModel/>
    </Window.DataContext>
    <Grid>
        <TextBox Text="{Binding Html}"/>
    </Grid>
</Window>

MainWindow.xaml.cs

namespace test{

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
}

public class ViewModel : INotifyPropertyChanged
{
    public string Html { get; set; }

    public ViewModel()
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://mp3.zing.vn");
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        if (response.StatusCode == HttpStatusCode.OK)
        {
            Stream receiveStream = response.GetResponseStream();
            StreamReader readStream = null;
            readStream = new StreamReader(receiveStream, Encoding.ASCII, true);
            Html = readStream.ReadToEnd();
            OnPropertyChanged("Html");
            response.Close();
            readStream.Close();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }   
}

}

I think this is because the web site uses compression and .NET does not expect/handle it correctly. This is probably because usually this is only done over HTTPS. Try over https... ie. https://mp3.zing.vn

If that does not solve your problem I suggest you do: request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip; request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;

Also, Make sure you use the right encoding...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM