[英]c# HttpWebRequest IOException
我正在使用以下功能導航到我的c#winform代碼中的URL地址。
我認為,代碼很好,但是當它嘗試建立與URL地址的連接時,它將失敗並拋出IOException錯誤 :
我的問題是:
如何在代碼中添加檢查以確保成功建立與URL的連接,如果未成功,則將重試直到成功建立連接?
public String WebRequestNavigate(string url)
{
StringBuilder sb = new StringBuilder();
byte[] buf = new byte[8192];
if (url != "")
{
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
myReq.KeepAlive = false;
try
{
HttpWebResponse resp = (HttpWebResponse)myReq.GetResponse();
Stream stream = resp.GetResponseStream();
String test = "";
int count = 0;
do
{
**count = stream.Read(buf, 0, buf.Length);**
if (count != 0)
{
test = Encoding.UTF8.GetString(buf, 0, count);
sb.Append(test);
}
}
while (count > 0);
stream.Close();
}
catch (WebException ex)
{
}
}
return sb.ToString();
}
感謝所有您的答案的朋友。 他們都是正確的。 但是,我終於找到了錯誤並糾正了它。
問題是我試圖捕獲WebException,但是,我得到了IOException錯誤。
我將WebException更改為IOException並更正了以下代碼:
catch (IOException ex)
{
System.Threading.Thread.Sleep(500);
myReq = (HttpWebRequest)WebRequest.Create(url);
myReq.KeepAlive = false;
}
我使用了您對Thread.Sleep的建議,以使我的代碼在嘗試建立新的URL連接之前等待。 這解決了我的問題%100。
抱歉,抽出寶貴的時間,但您對我的幫助很大,並提供了見解。 謝謝!
最簡單(但不一定是“最佳”)的方法是將其包裝在while循環中,並創建一個布爾變量來確認連接是否成功。 如果它永遠不會成功,那么ConnectionSucceeded
將永遠不會設置為true
。
public String WebRequestNavigate(string url)
{
StringBuilder sb = new StringBuilder();
byte[] buf = new byte[8192];
if (url != "")
{
bool ConnectionSucceeded;
while (!ConnectionSucceeded) {
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
myReq.KeepAlive = false;
try
{
HttpWebResponse resp = (HttpWebResponse)myReq.GetResponse();
Stream stream = resp.GetResponseStream();
String test = "";
int count = 0;
do
{
count = stream.Read(buf, 0, buf.Length);
if (count != 0)
{
test = Encoding.UTF8.GetString(buf, 0, count);
sb.Append(test);
}
}
while (count > 0);
stream.Close();
ConnectionSucceeded = true;
}
catch (WebException ex)
{
}
}
}
return sb.ToString();
}
一些類似但更簡單的東西:
Stream stream = null;
while (stream == null)
{
try
{
HttpWebResponse resp = (HttpWebResponse)myReq.GetResponse();
stream = resp.GetResponseStream();
}
catch (Exception e)
{
System.Threading.Thread.Sleep(500);
// plus idea: die after a few try?
}
}
我的建議是以類似於以下方式使用WebClient:
string result = "";
bool success = false;
int remainingAttempts = 5;
while(success == false && remainingAttempts > 0) {
remainingAttempts--;
try
{
WebClient client = new WebClient();
result = client.DownloadString(url);
success = true;
}
catch (WebException ex)
{
}
if(success == false) {
System.Threading.Thread.Sleep(1000);
}
}
請訪問http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx和http://msdn.microsoft.com/en-us/library/system.net.webexception.aspx參考。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.