Unity3D/Tips
[펌] How to 100% check internet availability
blueasa
2018. 6. 28. 16:30
Using this method you can see if you are able to view the page you wanted or not by accessing the html of that page you can read it to see if you got redirected or not. this example uses www.google.com as it's check
using System.Net;
public string GetHtmlFromUri(string resource)
{
string html = string.Empty;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(resource);
try
{
using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
{
bool isSuccess = (int)resp.StatusCode < 299 && (int)resp.StatusCode >= 200;
if (isSuccess)
{
using (StreamReader reader = new StreamReader(resp.GetResponseStream()))
{
//We are limiting the array to 80 so we don't have
//to parse the entire html document feel free to
//adjust (probably stay under 300)
char[] cs = new char[80];
reader.Read(cs, 0, cs.Length);
foreach(char ch in cs)
{
html +=ch;
}
}
}
}
}
catch
{
return "";
}
return html;
}
This is to call the function
using System.Net;
void Start()
{
string HtmlText = GetHtmlFromUri("http://google.com");
if(HtmlText == "")
{
//No connection
}
else if(!HtmlText.Contains("schema.org/WebPage"))
{
//Redirecting since the beginning of googles html contains that
//phrase and it was not found
}
else
{
//success
}
}
[출처] https://answers.unity.com/questions/567497/how-to-100-check-internet-availability.html
반응형