话不多说,直入正题。
先说node.js端
证书是我在腾讯云搞得,下载下来即可。上代码
node用的是express模块
var app = require('express')();
var fs = require('fs');
var http = require('http');
var https = require('https');
var privateKey = fs.readFileSync('3_sallen.cc.key');
var certificate = fs.readFileSync('2_sallen.cc.crt');
var credentials = {key: privateKey, cert: certificate};
var httpServer = http.createServer(app);
var httpsServer = https.createServer(credentials, app);
var PORT = 8000;
var SSLPORT = 8001;
httpServer.listen(PORT, function() {
console.log('HTTP Server is running on: http://localhost:%s', PORT);
});
httpsServer.listen(SSLPORT, function() {
console.log('HTTPS Server is running on: https://localhost:%s', SSLPORT);
});
app.get('/user', function(req, res) {
if(req.protocol === 'https') {
res.status(200).send('Welcome to sallen');
}
else {
res.status(200).send('Welcome!');
}
});
好了 下面是ios
后台给的证书crt的话 需要转换成cer
进到证书路径,执行下面语句 openssl x509 -in 你的证书.crt -out 你的证书.cer -outform der 这样你就可以得到cer类型的证书了
sallen是我转换的证书。
我用的是免费证书 所以在ios访问时以下错误,
所以需要在afnetworking里面注释掉下面
当然了 花钱的证书 应该是不需要的。
下面ios代码附上
NSString *url = @"your address";
NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"sallen" ofType:@"cer"];
NSData *certData =[NSData dataWithContentsOfFile:cerPath];
NSSet *certSet = [[NSSet alloc] initWithObjects:certData, nil];
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
// 设置证书
[securityPolicy setPinnedCertificates:certSet];
securityPolicy.allowInvalidCertificates = YES;
securityPolicy.validatesDomainName = YES;
// 初始化请求的manager对象
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.securityPolicy = securityPolicy;
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:url parameters:nil progress:^(NSProgress * progress){
} success:^(NSURLSessionDataTask *task, id responseObject) {
NSArray * array = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
NSLog(@"OK === %@",array);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(@"error ==%@",error.description);
}];
```