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

  1. using System.Net;
  2. public string GetHtmlFromUri(string resource)
  3. {
  4. string html = string.Empty;
  5. HttpWebRequest req = (HttpWebRequest)WebRequest.Create(resource);
  6. try
  7. {
  8. using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
  9. {
  10. bool isSuccess = (int)resp.StatusCode < 299 && (int)resp.StatusCode >= 200;
  11. if (isSuccess)
  12. {
  13. using (StreamReader reader = new StreamReader(resp.GetResponseStream()))
  14. {
  15. //We are limiting the array to 80 so we don't have
  16. //to parse the entire html document feel free to
  17. //adjust (probably stay under 300)
  18. char[] cs = new char[80];
  19. reader.Read(cs, 0, cs.Length);
  20. foreach(char ch in cs)
  21. {
  22. html +=ch;
  23. }
  24. }
  25. }
  26. }
  27. }
  28. catch
  29. {
  30. return "";
  31. }
  32. return html;
  33. }

This is to call the function

  1. using System.Net;
  2. void Start()
  3. {
  4. string HtmlText = GetHtmlFromUri("http://google.com");
  5. if(HtmlText == "")
  6. {
  7. //No connection
  8. }
  9. else if(!HtmlText.Contains("schema.org/WebPage"))
  10. {
  11. //Redirecting since the beginning of googles html contains that
  12. //phrase and it was not found
  13. }
  14. else
  15. {
  16. //success
  17. }
  18. }



[출처] https://answers.unity.com/questions/567497/how-to-100-check-internet-availability.html

반응형