0

我在本地机器上部署 docker 容器。我检查它们是否已成功部署的方法是转到我的浏览器并键入http://192.168.99.105:7474/browser. 我想以编程方式执行此操作,因此我遵循了此问题Check if a url is reachable - Help in optimization a Class 中的代码。但是,当我尝试时,我得到一个System.Net.WebException {"The remote server returned an error: (504) Gateway Timeout."}.

它工作正常,HttpStatusCode.OK如果网址是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

4

1 回答 1

2

您的代码很好,尽管使用新的 NuGet 包会更好Microsoft.Net.Http,它全部是异步的并且支持 .NET Core。

您的代码所做的与浏览器所做的唯一区别是请求中的 HTTP 方法。浏览器发送 aGET但您明确使用HEAD. 如果您只想测试连接性,那是最有效的方法 - 但服务器可能不支持HEAD请求(我对neo4j的了解不够好,无法确定)。

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

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

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

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

或者,如果您确定HEAD支持:

Invoke-WebRequest -Uri http://stackoverflow.com -Method Head -UseBasicParsing
于 2016-10-17T14:10:19.277 回答