我在尝试从http://mp3.zing.vn获取HTML代码时出现问题(其他网站没问题), 我收到的代码如this。请帮我解决这个问题。
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));
}
}
}
答案 0 :(得分:0)
我认为这是因为网站使用压缩而.NET并不期望/正确处理它。这可能是因为通常只通过HTTPS完成。试试https ...即。 https://mp3.zing.vn
如果这不能解决您的问题,我建议您这样做:
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
另外,请确保使用正确的编码...