我正在尝试使用RestSharp调用本地Bosch Smart Home API。 Bosch的文档显示了如何使用Postman通过HTTP请求本地API,并正确使用所有功能。创建自签名证书并相应设置邮递员后,我什至可以请求设备列表。因此,我尝试开发一个简单的C#代码以通过RestSharp请求相同的列表。
static void RestGet()
{
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
const String WEBSERVICE_URL = "https://10.20.1.41:8444/smarthome/devices";
const string certificate_path = @"C:\Users\niko\Documents\certificates\certificate.pfx";
const string certificate_pass = "....";
const string systemPassword = "...."; //encrypted in BASE64
string ua = "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0) Gecko/20100101 Firefox/8.0";
ServicePointManager.Expect100Continue = true;
ServicePointManager.DefaultConnectionLimit = 9999;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;
var client = new RestClient("https://10.20.1.41:8444/smarthome/devices");
client.Timeout = 100000;
X509Certificate2 cer = new X509Certificate2(certificate_path, certificate_pass);
client.ClientCertificates = new X509CertificateCollection() { cer };
var request = new RestRequest(Method.GET);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("api-version", "1.0");
request.AddHeader("Systempassword", systemPassword);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.ErrorMessage);
Console.WriteLine(response.Content);
Console.ReadKey();
}
由于某种原因,服务器仅发送错误消息“请求已中止:无法创建SSL / TLS安全通道。”。我一直在试图解决这一问题,但是由于API相当新,因此尚无任何信息。
所以一旦我注意到在Fiddler在后台打开时请求实际上会成功,我就知道我的错误一定是我如何将证书加载到程序中(因为Fiddler使用了您必须提供的单独证书)。注意到这一点后,我要做的第一件事是将我提供的Fiddler证书复制到我的项目中,然后将其加载到程序中。并最终成功!我无法告诉您该证书与其他证书有何不同。