Program Tip

WebClient + HTTPS 문제

programtip 2020. 11. 28. 10:19
반응형

WebClient + HTTPS 문제


현재 타사에서 만든 시스템과 통합하고 있습니다. 이 시스템에서는 XML / HTTPS를 사용하여 요청을 보내야합니다. 제 3자가 나에게 인증서를 보내고 설치했습니다.

다음 코드를 사용합니다.

using (WebClient client = new WebClient())
{
   client.Headers.Add(HttpRequestHeader.ContentType, "text/xml");

   System.Text.ASCIIEncoding  encoding=new System.Text.ASCIIEncoding();
   var response = client.UploadData(address, "POST", encoding.GetBytes(msg));
}

이 코드는 다음을 반환합니다 WebException.

기본 연결이 닫혔습니다. SSL / TLS 보안 채널에 대한 신뢰 관계를 설정할 수 없습니다.

업데이트 내가 작업중인 테스트 서버이기 때문에 인증서를 신뢰할 수없고 유효성 검사가 실패합니다 ... 테스트 / 디버그 환경에서이를 우회하려면 새ServerCertificateValidationCallback

ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(bypassAllCertificateStuff);

여기 내 "가짜"콜백이 있습니다.

private static bool bypassAllCertificateStuff(object sender, X509Certificate cert, X509Chain chain, System.Net.Security.SslPolicyErrors error)
{
   return true;
}

여기여기에서 더 많은 것을 읽으 십시오


모든 인증서를 허용하는 코드의 가장 짧은 표기법은 실제로 다음과 같습니다.

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

이 오류에 대해 잘 작동합니다. 물론 인증서를 실제로 확인하고 인증서 정보를 기반으로 통신이 안전한지 결정하는 구현을 제공해야한다는 것은 말할 필요도 없습니다. 테스트 목적으로 위의 코드 줄을 사용하십시오.


원래 답변의 VB.NET 버전의 경우 여기에 있습니다 ( 'AddressOf'연산자로 이벤트를 연결해야 할 때 변환기가 제대로 작동하지 않음). WebClient () 또는 HttpWebRequest () 객체를 사용하기 전에가는 첫 번째 코드 :

ServicePointManager.ServerCertificateValidationCallback = New System.Net.Security.RemoteCertificateValidationCallback(AddressOf bypassAllCertificateStuff)

.. 및 유선 메서드 코드 :

Private Shared Function bypassAllCertificateStuff(ByVal sender As Object, ByVal cert As X509Certificate, ByVal chain As X509Chain, ByVal [error] As System.Net.Security.SslPolicyErrors) As Boolean
    Return True
End Function

이것을 시도하면 작동합니다.

class Ejemplo
{
    static void Main(string[] args)
    {
        string _response = null;
        string _auth = "Basic";
        Uri _uri = new Uri(@"http://api.olr.com/Service.svc");

        string addres = @"http://api.olr.com/Service.svc";
        string proxy = @"http://xx.xx.xx.xx:xxxx";
        string user = @"platinum";
        string pass = @"01CFE4BF-11BA";


        NetworkCredential net = new NetworkCredential(user, pass);
        CredentialCache _cc = new CredentialCache();

        WebCustom page = new WebCustom(addres, proxy);
        page.connectProxy();

        _cc.Add(_uri, _auth, net);

        page.myWebClient.Credentials = _cc;

        Console.WriteLine(page.copyWeb());
    }

}

public class WebCustom
{
        private string proxy;
        private string url;
        public WebClient myWebClient;
        public WebProxy proxyObj;
        public string webPageData;


        public WebCustom(string _url, string _proxy)
        {
            url = _url;
            proxy = _proxy;
            myWebClient = new WebClient();
        }

        public void connectProxy()
        {
            proxyObj = new WebProxy(proxy, true);
            proxyObj.Credentials = CredentialCache.DefaultCredentials;
            myWebClient.Proxy = proxyObj;
        }

        public string copyWeb()
        { return webPageData = myWebClient.DownloadString(url); }
}

참고 URL : https://stackoverflow.com/questions/536352/webclient-https-issues

반응형