0

I'm trying to use use WinInet to make HTTP requests and HttpSendRequest() sometimes returns a failure while other applications and browsers seem to have internet access.
When I check GetLastError() it returns 2. This isn't one of the standard WinInet error codes, but it could be the Win32 ERROR_FILE_NOT_FOUND.

This is failing with multiple pieces of code but here's one I could easily test with:

'Split up the URL into its component parts
URLInfo = SplitURL(URL)
AuthFlags = IIf(URLInfo.lpszUserName = "" And URLInfo.lpszPassword = "", INTERNET_FLAG_NO_AUTH, 0)

'Create the connection to the server
SessionHandle = InternetConnect(InetHandle, URLInfo.lpszHostName, URLInfo.nPort, URLInfo.lpszUserName, URLInfo.lpszPassword, URLInfo.nScheme, AuthFlags, 0)
If SessionHandle = 0 Then
  Err.Raise HTTPErrorInitSession, , "Failed to initialise the HTTP session: " & Cstr(Err.LastDllError)
End If

'Create the request for the resource
RequestHandle = HttpOpenRequest(SessionHandle, IIf(PostData = "", "GET", "POST"), URLInfo.lpszUrlPath & URLInfo.lpszExtraInfo, "HTTP/1.1", vbNullString, vbNullString, INTERNET_FLAG_RELOAD Or INTERNET_FLAG_NO_CACHE_WRITE Or AuthFlags, 0)
If RequestHandle = 0 Then
  Err.Raise HTTPErrorInitRequest, , "Failed to initialise the HTTP request: " & Cstr(Err.LastDllError)
End If

'Send the request
RequestSent = (HttpSendRequest(RequestHandle, SendHeaders, Len(SendHeaders), vbNullString, 0) = 1)
'Wait for the "success" message
If Not RequestSent Then
  Err.Raise HTTPErrorNoHost, , "Failed to connect to the HTTP server: " & Cstr(Err.LastDllError)
End If

I've tried running a packet capture and looking at network traffic when it fails and it doesn't even try to make the connection.

What's going on here and why does it seem to occur randomly?

4

1 回答 1

1

HttpSendRequest() will fail with an error code of 2 (ERROR_FILE_NOT_FOUND) when Windows/Internet Explorer is set to "Work offline" and the resource is not in the offline cache.

This doesn't seem to effect .Net based HTTP clients or other web browsers like FireFox or Chrome making it not immediatly obvious if Internet Explorer is not the primary or default browser.

You can go back "online" by opening up Internet Explorer, going to the file menu (pressing Alt if it's not visible), and unticking "Work offline". After this, programmatic attempts to use WinInet will work correctly.

Note that Windows/Internet Explorer can get into this state accidentally if you set up dial up/VPN connections for testing or occasional use and its not set to "Never dial a connection"

于 2013-09-04T10:23:35.113 回答