Home > Back-end >  How to read that from from a website and do something
How to read that from from a website and do something

Time:12-11

I want to read the data from a website like if on the website says SAY_HELLO to display a message box which says hello world or if it says SAY_HELLOME to display a message box that says Hello me

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

CodePudding user response:

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");

CodePudding user response:

It would be best if you did not use WebClient, It's obsolete now, Refer the below.

[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);
    }
}

Instead, it would be best if you use HttpClient. It also provides async methods as well.

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");

You could also use string webContent = await wc.GetStringAsync(webURL);. there is no need to first get the byte array and then convert to string. Note: I have not tested the code, but it should work.

  • Related