我在本地计算机上部署docker容器。通过我的浏览器并键入http://192.168.99.105:7474/browser
,我可以检查它们是否已成功部署。我想以编程方式执行此操作,因此我遵循了Check if a url is reachable - Help in optimizing 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
最佳答案
您的代码很好,尽管最好使用新的Microsoft.Net.Http
NuGet软件包,该软件包是异步的并且支持.NET Core。
代码和浏览器之间的唯一区别是请求中的HTTP方法。浏览器发送GET
,但您明确使用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
关于c# - 如何检查本地URL是否可访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40086982/