我对HttpWebRequest
有一个问题。我正在尝试通过网络服务和带有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()
呼叫期间卡住了吗?我要说的是我是一个代理人,所以我想到了代理可能会阻止某些请求的想法,可以吗?
好吧,我想出了类似的东西:
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>
我现在该怎么办?