Jump to content

Chamada APi Rest com autenticação via certificado


Delphi_852

Recommended Posts

Boa Tarde,

Necessito fazer aplicação que faz pedido através da api Rest permita obter dados do servidor. Esta chamada utiliza autenticação através de um certificado digital...

porém não estou a conseguir... obtenho o seguinte erro: "The request was aborted: Could not create SSL/TLS secure channel.".. Alguém me pode ajudar??

Segue parte do meu código....

Appi.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>


  <system.net>
    
    <settings>
      
      <httpWebRequest useUnsafeHeaderParsing="true" />
    </settings>

    <defaultProxy>

      <proxy   bypassonlocal="True"  usesystemdefault="False" />

    </defaultProxy>


  </system.net>

</configuration>

 

 

public enum HttpVerb
{
    GET,
    POST,
    PUT,
    DELETE
}

namespace HttpUtils
{
    public class RestClient
    {
        public string EndPoint { get; set; }
        public HttpVerb Method { get; set; }
        public string ContentType { get; set; }
        public string PostData { get; set; }

        public RestClient()
        {
            EndPoint = "";
            Method = HttpVerb.GET;
            ContentType = "text/xml";
            PostData = "";
        }
        public RestClient(string endpoint)
        {
            EndPoint = endpoint;
            Method = HttpVerb.GET;
            ContentType = "text/xml";
            PostData = "";
        }
        public RestClient(string endpoint, HttpVerb method)
        {
            EndPoint = endpoint;
            Method = method;
            ContentType = "text/xml";
            PostData = "";
        }

        public RestClient(string endpoint, HttpVerb method, string postData)
        {
            EndPoint = endpoint;
            Method = method;
            ContentType = "text/xml";
            PostData = postData;
        }


        public string MakeRequest()
        {
            return MakeRequest("");
        }

        public string MakeRequest(string parameters)
        {

            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;


            var request = (HttpWebRequest)WebRequest.Create(EndPoint + parameters);

            string certFileName = Path.Combine("C:\\....", "cert.p12");

            request.ProtocolVersion = HttpVersion.Version10;

            X509Certificate2 cert = new X509Certificate2(certFileName, "pass");

            request.KeepAlive = false;
            request.ServicePoint.Expect100Continue = false;


            request.Method = Method.ToString();
            request.ContentLength = 0;
            request.ContentType = ContentType;

            request.ClientCertificates.Add(cert);
            request.PreAuthenticate = true;

            if (!string.IsNullOrEmpty(PostData) && Method == HttpVerb.POST)

            {
                var encoding = new UTF8Encoding();
                var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(PostData);
                request.ContentLength = bytes.Length;

                using (var writeStream = request.GetRequestStream())
                {
                    writeStream.Write(bytes, 0, bytes.Length);
                }
            }

            using (var response = (HttpWebResponse)request.GetResponse())
            {
                var responseValue = string.Empty;

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
                    throw new ApplicationException(message);
                }

                // grab the response
                using (var responseStream = response.GetResponseStream())
                {
                    if (responseStream != null)
                        using (var reader = new StreamReader(responseStream))
                        {
                            responseValue = reader.ReadToEnd();
                        }
                }

                return responseValue;
            }
        }

    } // class

}

E a chamada:

string endPoint = @"https://......./json";
            var client = new RestClient(endPoint);
            var json = client.MakeRequest();

 

 

Obrigado pela atenção...


 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.