winforms 如何从网站上读到并做一些事情

bprjcwpo  于 2022-12-14  发布在  其他
关注(0)|答案(2)|浏览(154)

我想从网站读取数据,例如,如果网站上显示SAY_HELLO,则会显示一个消息框,其中显示hello world,如果显示SAY_HELLOME,则会显示一个消息框,其中显示Hello me

WebClient client = new WebClient();
            Stream str = client.OpenRead("http://localhost/api/maintenance.php");
            StreamReader reader = new StreamReader(str);
            String content = reader.ReadToEnd();
9rygscc1

9rygscc11#

string webURL = "http://localhost/api/maintenance.php";
WebClient wc = new WebClient();
wc.Headers.Add("user-agent", "Only a Header!");
byte[] rawByteArray = wc.DownloadData(webURL);
string webContent = Encoding.UTF8.GetString(rawByteArray);

if (webContent.ToUpper().Contains("SAY_HELLO"))
     MessageBox.Show("hello world");
else if (webContent.ToUpper().Contains("SAY_HELLOME"))
     MessageBox.Show("hello me");
pepwfjgg

pepwfjgg2#

最好不要使用WebClient,它现在已经过时了,请参考下面的。

[Obsolete(Obsoletions.WebRequestMessage, DiagnosticId = Obsoletions.WebRequestDiagId, UrlFormat = Obsoletions.SharedUrlFormat)]
public WebClient()
{
    // We don't know if derived types need finalizing, but WebClient doesn't.
    if (GetType() == typeof(WebClient))
    {
        GC.SuppressFinalize(this);
    }
}

相反,最好使用HttpClient,它还提供异步方法。

string webURL = "http://localhost/api/maintenance.php";
HttpClient wc = new HttpClient();
wc.DefaultRequestHeaders.Add("user-agent", "Only a Header!");
byte[] rawByteArray = await wc.GetByteArrayAsync(webURL);
string webContent = Encoding.UTF8.GetString(rawByteArray);

if (webContent.ToUpper().Contains("SAY_HELLO"))
     MessageBox.Show("hello world");
else if (webContent.ToUpper().Contains("SAY_HELLOME"))
     MessageBox.Show("hello me");

您也可以使用string webContent = await wc.GetStringAsync(webURL);。不需要先取得字节数组,然后再转换成字串。注意:我还没有测试代码,但它应该工作。

相关问题