Har*_*pta 2 c# httprequest unity-game-engine
我正在 Unity 中编写一个简单的代码,以检查我是否能够通过我的应用程序访问网站。这是我写的代码:
IEnumerator CheckInternetPing()
{
WWW wwwInternet = new WWW("http://google.com");
yield return wwwInternet;
if (wwwInternet.bytesDownloaded == 0)
{
//yield return new WaitForSeconds(1f);
Debug.Log("Not Connected to Internet");
}
else
{
Debug.Log("Connected to Internet");
internetMenu.SetActive(false);
}
}
Run Code Online (Sandbox Code Playgroud)
我发现了一个错误,如果我在互联网上运行它,它会显示“已连接”,但是当我关闭互联网并立即运行该应用程序时,它不会记录任何内容。仅当我再次重新启动应用程序时,它才会显示“未连接”。有谁知道为什么它在第一次没有记录任何内容?谢谢
这是类的一个错误,WWW已经在这里很久了。每个设备的行为可能都不同。如果禁用 Wifi,它曾经在编辑器上冻结。快速测试表明此错误尚未修复。
您需要使用HttpWebRequest而不是WWW.
在下面的例子中,Thread用于避免请求阻塞 Unity 程序,UnityThread用于在请求完成时回调到 Unity 主线程。UnityThread从这个帖子中获取。
void Awake()
{
//Enable Callback on the main Thread
UnityThread.initUnityThread();
}
void isOnline(Action<bool> online)
{
bool success = true;
//Use ThreadPool to avoid freezing
ThreadPool.QueueUserWorkItem(delegate
{
try
{
int timeout = 2000;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://google.com");
request.Method = "GET";
request.Timeout = timeout;
request.KeepAlive = false;
request.ServicePoint.Expect100Continue = false;
request.ServicePoint.MaxIdleTime = timeout;
//Make sure Google don't reject you when called on mobile device (Android)
request.changeSysTemHeader("User-Agent", "Mozilla / 5.0(Windows NT 10.0; WOW64) AppleWebKit / 537.36(KHTML, like Gecko) Chrome / 55.0.2883.87 Safari / 537.36");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response == null)
{
success = false;
}
if (response != null && response.StatusCode != HttpStatusCode.OK)
{
success = false;
}
}
catch (Exception)
{
success = false;
}
//Do the callback in the main Thread
UnityThread.executeInUpdate(() =>
{
if (online != null)
online(success);
});
});
}
Run Code Online (Sandbox Code Playgroud)
您需要changeSysTemHeader允许更改“User-Agent”标头的函数的扩展类:
public static class ExtensionMethods
{
public static void changeSysTemHeader(this HttpWebRequest request, string key, string value)
{
WebHeaderCollection wHeader = new WebHeaderCollection();
wHeader[key] = value;
FieldInfo fildInfo = request.GetType().GetField("webHeaders",
System.Reflection.BindingFlags.NonPublic
| System.Reflection.BindingFlags.Instance
| System.Reflection.BindingFlags.GetField);
fildInfo.SetValue(request, wHeader);
}
}
Run Code Online (Sandbox Code Playgroud)
使用起来非常简单:
void Start()
{
isOnline((online) =>
{
if (online)
{
Debug.Log("Connected to Internet");
//internetMenu.SetActive(false);
}
else
{
Debug.Log("Not Connected to Internet");
}
});
}
Run Code Online (Sandbox Code Playgroud)