我对HttpWebRequest
有些疑问。我正在尝试管理带有WebService的服务器和带有CF 2.0客户端的Windows CE 6.0之间的连接,我的实际目的是检索Windows CE计算机的外部IP。我曾尝试使用HttpWebResponse
,但在通话过程中卡住了。
现在我会更清楚,这是我在WinCE机器上运行以获取IP的代码:
private string GetIPAddressRemote()
{
Uri validUri = new Uri("http://icanhazip.com");
try
{
string externalIP = "";
HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(validUri);
httpRequest.Credentials = CredentialCache.DefaultCredentials;
httpRequest.Timeout = 10000; // Just to haven't an endless wait
using (HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse())
/* HERE WE ARE
* In this point my program stop working...
* well actually it doesn't throw any exception and doesn't crash at all
* For that reason I've setted the timeout property because in this part
* it starts to wait for a response that doesn't come
*/
{
using (Stream stream = httpResponse.GetResponseStream())
{
// retrieve the return string and
// save it in the externalIP variable
}
}
return externalIP;
}
catch(Exception ex)
{
return ex.Message;
}
}
那么,我的问题是什么?我不知道为什么它会在httpRequest.GetResponse()
电话中卡住,任何想法?
我要说我是代理人,所以我想出了代理可以阻止某些请求的想法,可能是吗?
答案 0 :(得分:0)
好的,我想出了类似的东西:
private string GetIPAddressRemote()
{
Uri validUri = new Uri("http://icanhazip.com/");
int tryNum = 0;
while (tryNum < 5)
{
tryNum++;
try
{
string externalIP = "";
WebProxy proxyObj = new WebProxy("http://myProxyAddress:myProxyPort/", true); // Read this from settings
WebRequest request = WebRequest.Create(validUri);
request.Proxy = proxyObj;
request.Credentials = CredentialCache.DefaultCredentials;
request.Timeout = 10000; // Just to haven't an endless wait
using (WebResponse response = request.GetResponse())
{
Stream dataStream = response.GetResponseStream();
using (StreamReader reader = new StreamReader(dataStream))
{
externalIP = reader.ReadToEnd();
}
}
return externalIP;
}
catch (Exception ex)
{
if(tryNum > 4)
return ex.Message;
}
Thread.Sleep(1000);
}
return "";
}
但现在的问题是没有任何信息需要检索。我的意思是,我从Stream
解析的字符串是html
页面,检索的字符串是:
<html>
<body>
<h1>It works!</h1>
<p>This is the default web page for this server.</p>
<p>The web server software is running but no content has been added, yet.</p>
</body>
</html>
我现在能做什么?