最近公司要對接電信物聯網北向API接口,當調用Auth受權接口時,須要用到證書,此篇文章記錄下遇到的坑~服務器
有兩種調用接口的方式,下面是兩種方式的簡單示例app
一、使用
HttpClient
url
public static void Post(string appId, string secret) { var handler = new HttpClientHandler { ClientCertificateOptions = ClientCertificateOption.Manual, SslProtocols = SslProtocols.Tls12, ServerCertificateCustomValidationCallback = (x, y, z, m) => true, }; var path = Path.Combine(AppContext.BaseDirectory, "cert\\iot3rd.p12"); handler.ClientCertificates.Add(new X509Certificate2(path, "IoM@1234")); var client = new HttpClient(handler); var content = new StringContent($"appId={appId}&secret={secret}"); content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); var httpResponseMessage = client.PostAsync("https://180.101.147.89:8743/iocm/app/sec/v1.1.0/login", content).GetAwaiter().GetResult(); var result = httpResponseMessage.Content.ReadAsStringAsync().GetAwaiter().GetResult(); Console.WriteLine(result); }
二、使用
HttpWebRequest
code
public static string Post(string appId, string secret) { ServicePointManager.ServerCertificateValidationCallback = (x, y, z, m) => true; ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create("https://180.101.147.89:8743/iocm/app/sec/v1.1.0/login"); var p12certfile = Path.Combine(AppContext.BaseDirectory, "cert\\iot3rd.p12"); X509Certificate2 cerCaiShang = new X509Certificate2(p12certfile, "IoM@1234"); httpRequest.ClientCertificates.Add(cerCaiShang); httpRequest.Method = "POST"; httpRequest.ContentType = "application/x-www-form-urlencoded"; Stream requestStem = httpRequest.GetRequestStream(); StreamWriter sw = new StreamWriter(requestStem); sw.Write($"appId={appId}&secret={secret}"); sw.Close(); HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse(); Stream receiveStream = httpResponse.GetResponseStream(); string result = string.Empty; using (StreamReader sr = new StreamReader(receiveStream)) { return sr.ReadToEnd(); } }
須要注意一點,上面兩種方式都須要設置服務器證書驗證回調方法,不然回報下面的異常orm
The remote certificate is invalid according to the validation procedure.
並且兩種方式的設置方式不同,HttpClient
是經過HttpClientHandler
對象的ServerCertificateCustomValidationCallback
屬性設置的,而HttpWebRequest
方式是經過ServicePointManager.ServerCertificateValidationCallback
來設置的對象