I have a method that works fine for uploading a file to an HTTPS server directly. However, if the customer site requires the customer go through a proxy server, it no longer works. I'd like to support the default proxy server as defined by the default browser. This seems to be the typical way it is set up.
The inital (non-proxy) code:
char CFHI_Network::UploadFileNoProxy(CString FileName, CString csUrlFullPath)
{
String^ urlString = gcnew String(csUrlFullPath);
String^ fileName = gcnew String(FileName);
WebClient^ myWebClient = gcnew WebClient;
// add credentials for https
NetworkCredential^ myCred = gcnew NetworkCredential(DEFAULT_LOGIN, DEFAULT_PASSWORD);
CredentialCache^ myCache = gcnew CredentialCache();
myCache->Add(gcnew Uri(urlString), "Basic", myCred);
myWebClient->Credentials = myCache;
try
{
cli::array<unsigned char>^ responseArray = myWebClient->UploadFile(urlString, "Put", fileName);
}
catch ( WebException^ ex )
{
// blah blah
}
catch (System::Exception^ ex)
{
// blah blah
}
return 1;
}
To add support for the browsers default proxy, it seems that I could grab the proxy from a WebRequest to the same URI as follows:
char CFHI_Network::UploadFileViaProxy(CString FileName, CString csUrlFullPath)
{
HttpWebRequest^ myReq;
CString csProxyUriString;
String^ urlProxyString;
String^ urlString = gcnew String(csUrlFullPath);
String^ fileName = gcnew String(FileName);
WebClient^ myWebClient = gcnew WebClient;
// add credentials for https
NetworkCredential^ myCred = gcnew NetworkCredential(DEFAULT_LOGIN, DEFAULT_PASSWORD);
CredentialCache^ myCache = gcnew CredentialCache();
myCache->Add(gcnew Uri(urlString), "Basic", myCred);
myWebClient->Credentials = myCache;
// now try to add support for default proxy
try
{
myReq = dynamic_cast<HttpWebRequest^>(WebRequest::Create(urlString));
}
catch (System::Exception^ ex)
{
// blah blah
}
// do proxy stuff here
IWebProxy^ myProxy = gcnew WebProxy;
// Obtain the Proxy Prperty of the Default browser.
myProxy = (IWebProxy^)(myReq->Proxy);
if (myProxy)
{
csProxyUriString = (myProxy->GetProxy(myReq->RequestUri))->ToString();
// I have a proxy and the path is: csProxyUriString
}
// Add the proxy to the WebClient
myWebClient->Proxy = myProxy;
try
{
cli::array<unsigned char>^ responseArray = myWebClient->UploadFile(urlString, "Put", fileName);
}
catch (System::Exception^ ex)
{
// blah blah
}
return 1;
}
Is there anything wrong with this approach?
Or, is there a simpler way to add Proxy support to a WebClient?