Referring to following code, when I directly paste url into browser, I can download file, but when I run following code, it gets error and I would like to know on what wrong it is.
Does anyone have any suggestions?
Thanks in advance for any suggestions
$clnt = new-object System.Net.WebClient
$url = "https://rbwm-api.hsbc.com.hk/digital-pws-tools-mpf-eapi-prod-proxy/v1/mpf/unit-prices/download/HSBCTRUSTPLUS?fund=APF&startDate=2018-10-17&endDate=2019-07-22&locale=zh_HK"
$file = "D:\Folder\ABC.xls"
try {
$request = [System.Net.WebRequest]::Create($url)
$request.Method = 'HEAD'
$response = $request.GetResponse()
$httpStatus = $response.StatusCode
$urlIsValid = ($httpStatus -eq 'OK')
$tryError = $null
$response.Close()
$clnt.DownloadFile($url,$file)
# leave the loop if successfull
}
catch [System.Exception] {
$httpStatus = $null
$tryError = $_.Exception
$urlIsValid = $false;
Write-Host "Error"
}
I just tried below code and it’s working.
[pre]
add-type @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
public bool CheckValidationResult(
ServicePoint srvPoint, X509Certificate certificate,
WebRequest request, int certificateProblem) {
return true;
}
}
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]‘Ssl3,Tls,Tls11,Tls12’
$url = “https://rbwm-api.hsbc.com.hk/digital-pws-tools-mpf-eapi-prod-proxy/v1/mpf/unit-prices/download/HSBCTRUSTPLUS?fund=APF&startDate=2018-10-17&endDate=2019-07-22&locale=zh_HK”
$file = “C:\Temp\ABC.xls”
$IE = New-Object System.Net.WebClient
$IE.DownloadFile($url,$file)
[/pre]
This should work for you as well.
$Webpkg = "$env:USERPROFILE\Documents"
$webclient = New-Object System.Net.WebClient
$url = "https://rbwm-api.hsbc.com.hk/digital-pws-tools-mpf-eapi-prod-proxy/v1/mpf/unit-prices/download/HSBCTRUSTPLUS?fund=APF&startDate=2018-10-17&endDate=2019-07-22&locale=zh_HK"
$file = "$Webpkg\ABC.xls"
$webclient.DownloadFile($url,$file)
Thanks, to everyone very much for suggestions (^v^)