我有一个奇怪的问题,我的应用程序正在尝试执行HTTPWebRequest POST来调用API。通常这没有问题,但是如果用户将他们的笔记本电脑带回家并通过他们的家庭网络连接,然后休眠机器并在第二天返回工作,HTTPWebRequest失败并出现超时错误或仅仅是URL无法到达。一旦他们重新启动笔记本电脑,连接通常会再次正常。
我花了很多天试图弄清楚可能导致这种情况的原因,例如笔记本电脑中的代理连接问题或网卡问题,但尚未成功诊断或修复。
任何人都对问题可能是什么或如何更好地诊断这个问题有任何建议?
代码:
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
答案 0 :(得分:0)
似乎不同的代理需要使用Net.HttpWebRequest对象的Proxy属性进行不同的配置,甚至不同的连接类型WiFi / LAN的行为也不同。
在大多数情况下,不使用它可以正常工作,但是我们发现有时你需要专门将Proxy.Credentials设置为默认值,因为它无法自动获取它们,而在其他情况下,它更容易设置代理=没有什么可以完全绕过它。
为了考虑所有场景,我们将所有三个嵌入到代码中,并传入一个ByRef proxyType变量,该变量存储连接正常的最新一个(作为整数)。在每个HttpRequest上,如果它失败,那么在其中一个工作的情况下循环其他方法,如果是,则将其传递回变量以在下一个调用中使用。如果在X次尝试后都失败,则引发异常。
我原始问题中的代码执行此操作,只需确保每次都正确传回proxyType变量!