我有一個奇怪的問題,我的應用程序嘗試執行HTTPWebRequest POST來調用API。通常情況下,這並沒有問題,但是如果用戶將筆記本電腦帶回家並通過家庭網絡連接,然後休眠機器並在第二天返回工作,則HTTPWebRequest將失敗,並出現超時錯誤或者僅僅是URL無法被達到。只要他們重新啓動筆記本電腦,連接通常會再次正常。httpWebRequest超時/筆記本休眠和交換網絡後連接失敗
我花了很多天試圖找出可能導致此問題的原因,例如筆記本電腦中的代理連接問題或網卡問題,但尚未成功進行診斷或修復。
任何人有什麼問題可能會有什麼建議,或者我怎麼能更好地診斷這個?
代碼:
Private Function WRequestMainDynamic(URL As String, method As String, POSTdata As String, timeout As Integer, Optional ByRef proxyType As Integer = 0)
Dim responseData As String = ""
Dim hwrequest As Net.HttpWebRequest = Nothing
Dim postByteArray() As Byte = Nothing
Dim connectionSuccess As Boolean = False
Dim count As Integer = 0
While connectionSuccess = False And count < 6
Try
hwrequest = Net.WebRequest.Create(URL)
hwrequest.Accept = "*/*"
hwrequest.AllowAutoRedirect = True
hwrequest.UserAgent = "http_requester/0.1"
hwrequest.Timeout = timeout
hwrequest.Method = method
hwrequest.KeepAlive = True
Select Case proxyType
Case 0
hwrequest.Proxy = Nothing
Case 1
'don't set anything
Case 2
hwrequest.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials
Case Else
hwrequest.Proxy = Nothing
End Select
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls Or SecurityProtocolType.Ssl3
ServicePointManager.Expect100Continue = False
If hwrequest.Method = "POST" Then
hwrequest.ContentType = "application/json"
Dim encoding As New Text.UTF8Encoding() 'Use UTF8Encoding for XML requests
postByteArray = encoding.GetBytes(POSTdata)
hwrequest.ContentLength = postByteArray.Length
Using postStream As IO.Stream = hwrequest.GetRequestStream()
postStream.Write(postByteArray, 0, postByteArray.Length)
End Using
End If
Using hwresponse As Net.HttpWebResponse = hwrequest.GetResponse()
If hwresponse.StatusCode = Net.HttpStatusCode.OK Then
Using responseStream As IO.StreamReader = New IO.StreamReader(hwresponse.GetResponseStream())
responseData = responseStream.ReadToEnd()
End Using
End If
End Using
connectionSuccess = True
Catch webex As WebException
If webex.Status = WebExceptionStatus.Timeout Then
Throw
Else
proxyType += 1
If proxyType = 3 Then proxyType = 0
count += 1
If count = 6 Then Throw
End If
Catch e As Exception
Throw
responseData = ""
Finally
postByteArray = Nothing
hwrequest = Nothing
GC.Collect()
End Try
End While
使用system.net日誌記錄功能(http://ferozedaud.blogspot.com/2009/08/tracing-with-systemnet.html)查看它在休眠後嘗試連接的服務器。 – feroze
謝謝我如何添加/整合這個配置文件與我的應用程序(Outlook加載項目),我有一個app.config文件,這是我應該添加它? – moatak787
是的,將它添加到您的控件的app.config文件。 – feroze