如何检查本地URL是否可达

我在我的本地机器上部署Docker容器。 他们的方式,我检查他们是否成功部署是通过去我的浏览器和键入http://192.168.99.105:7474/browser 。 我想这样做以编程方式,所以我跟着这个问题的代码检查一个URL是否可达 – 帮助优化一个类 。 但是,当我尝试它,我得到一个System.Net.WebException {"The remote server returned an error: (504) Gateway Timeout."}

它工作正常,但我得到一个HttpStatusCode.OK如果该url是https://en.wikipedia.org/wiki/YouTube

这是我的代码:

 private bool UrlIsReachable(string url) { //https://en.wikipedia.org/wiki/YouTube HttpWebRequest request = WebRequest.Create("http://192.168.99.105:7474/browser") as HttpWebRequest; request.Timeout = 600000;//set to 10 minutes, includes time for downloading the image request.Method = "HEAD"; try { using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { return response.StatusCode == HttpStatusCode.OK; } } catch (WebException) { return false; } } 

编辑:我的docker-compose.yml文件

 version: '2' services: company1: image: neo4j ports: - "7474:7474" - "7687:7687" volumes: - $HOME/company1/data:/data - $HOME/company1/plugins:/plugins company2: image: neo4j ports: - "7475:7474" - "7688:7687" volumes: - $HOME/company2/data:/data - $HOME/company2/plugins:/plugins 

你的代码是好的,尽pipe最好使用新的Microsoft.Net.Http NuGet包,它是所有asynchronous的并且支持.NET Core。

你的代码和浏览器的唯一区别就是请求中的HTTP方法。 浏览器发送一个GET但你明确地使用HEAD 。 如果你只想testing连通性,这是最有效的方法 – 但是服务器可能不支持HEAD请求(我不知道neo4j是否足够确定)。

尝试在您的代码中使用GET请求 – 此示例使用新的asynchronous方法:

  [TestMethod] public async Task TestUrls() { Assert.IsTrue(await UrlIsReachable("http://stackoverflow.com")); Assert.IsFalse(await UrlIsReachable("http://111.222.333.444")); } private async Task<bool> UrlIsReachable(string url) { try { using (var client = new HttpClient()) { var response = await client.GetAsync(url); return response.StatusCode == HttpStatusCode.OK; } } catch { return false; } } 

尽pipe自动化testing最简单的方法是使用PowerShell,而不是编写自定义应用程序:

 Invoke-WebRequest -Uri http://stackoverflow.com -UseBasicParsing 

或者,如果您确定支持HEAD

 Invoke-WebRequest -Uri http://stackoverflow.com -Method Head -UseBasicParsing