title: How to reset WinHTTP proxy credentials after a failed request?
body: <p>I need to write code to download a file and the requirements are as follows.  If the application is configured to use a proxy, attempt to download via the proxy.  If that fails, attempt a direct connection.  If no proxy is configured, attempt a direct connection.  High-level pseudo-code:</p>
  
  <pre><code>if(ProxyEnabled)
      if(!DownloadWithProxy())
          DownloadWithoutProxy()
  else
      DownloadWithoutProxy()
  </code></pre>
  
  <p>I'm using WinHTTP since this code will be running in a service.  The actual downloading is straightforward but I'm having issues with the proxy settings.  My current pseudo-code is as follows:</p>
  
  <pre><code>hSession = WinHttpOpen(..., WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, ...)
  hConnect = WinHttpConnect(hSession, ...)
  hRequest = WinHttpOpenRequest(hConnect, ...)
  if(Proxy.Enabled)
  {
      // set proxy server
      WinHttpSetOption(hRequest, WINHTTP_OPTION_PROXY, ServerName)
      // set proxy credentials
      WinHttpSetCredentials(hRequest, WINHTTP_AUTH_TARGET_PROXY, UserName, Password)
      if(!DownloadFile(hRequest))
      {
          // reset proxy server
          WinHttpSetOption(hRequest, WINHTTP_OPTION_PROXY, NULL)
          // reset proxy credentials
          WinHttpSetCredentials(hRequest, WINHTTP_AUTH_TARGET_PROXY, NULL, NULL)
          DownloadFile(hRequest)
      }
  }
  else
  {
      DownloadFile(hRequest)
  }
  </code></pre>
  
  <p>Where <code>DownloadFile()</code> does the standard <code>WinHttpSendRequest()</code> and <code>WinHttpReceiveResponse()</code> sequence.  Everything works fine except in the case where the download via the proxy fails.  When that happens the call to <code>WinHttpSetCredentials()</code> to reset the credentials fails (with ERROR_INVALID_PARAMETER), and as a result the second call to <code>DownloadFile()</code> still tries to use the proxy (even though I reset it) and the credentials.  NOTE: In this specific scenario I am using a valid proxy server but invalid proxy credentials to trigger the failure.</p>
  
  <p>So I guess my question is what is the best approach?  As far as I can tell it is not possible to reset the credentials set via <code>WinHttpSetCredentials()</code>, so I guess I should just recreate the request for each call to <code>DownloadFile()</code> rather than trying to be "clever" by reusing a single request object.</p>