我正在使用 WebClient 尝试从本地连接到我的 PC 的硬件中获取字符串响应。我的 PC 有一个连接到 LAN 的网络适配器和一个仅连接到我的硬件的第二个适配器。
如果我使用带有 URL 的 IE:http://169.254.103.127/set.cmd?user=admin+pass=12345678+cmd=getpower我会得到一个字符串作为响应。我正在尝试使用以下代码片段来实现相同的目的:
using (WebClient client = new WebClient())
{
client.Proxy = WebRequest.DefaultWebProxy;
client.Credentials = CredentialCache.DefaultCredentials;
client.Proxy.Credentials = CredentialCache.DefaultCredentials;
client.Headers["User-Agent"] =
"Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0) " +
"(compatible; MSIE 6.0; Windows NT 5.1; " +
".NET CLR 1.1.4322; .NET CLR 2.0.50727)";
String test = client.DownloadString(@"http://169.254.103.127/set.cmd?user=admin+pass=12345678+cmd=getpower");
}
Run Code Online (Sandbox Code Playgroud)
如果我禁用连接到 LAN 的网络适配器,则此代码段有效,否则会超时。
有人可以解释为什么会发生这种情况以及我需要做什么才能将请求路由到正确的网络吗?
将代理设置为 null 解决了我的问题,这是完成的功能:
private String SendCommand(String command)
{
String response = null;
using (WebClient client = new WebClient())
{
client.Proxy = null;
response = client.DownloadString(command);
}
return response;
}
Run Code Online (Sandbox Code Playgroud)