afnetworking使用https
Posted 蜡笔小斌
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了afnetworking使用https相关的知识,希望对你有一定的参考价值。
背景:
- 在开发环境下,HTTPS一般使用自行颁发的证书
- AFNetworking3 使用HTTPS协议时,需要针对自行颁发的证书作一定配置
- 我在配置过程中发现网上的信息多少都有疏漏
1.nginx HTTPS配置
1.1使用以下命令生成server.key,server.csr,server.crt三个文件
openssl req -new -nodes -keyout server.key -out server.csr
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
1.2Nginx配置文件例子
upstream api
server 127.0.0.1:4000 fail_timeout=0;
server
listen 3000;
server_name localhost;
root /vagrant/grape-api/public;
try_files $uri/index.html $uri @api;
location @api
proxy_pass http://api;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
error_page 500 502 503 504 /500.html;
client_max_body_size 4G;
keepalive_timeout 10;
!!!注意这里一系列的ssl配置
ssl on;
ssl_certificate /home/vagrant/server.crt; 这是上一步生成的crt文件路径
ssl_certificate_key /home/vagrant/server.key;这是上一步生成的key文件路径
ssl_session_timeout 5m;
ssl_protocols SSLv2 SSLv3 TLSv1;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
重启Nginx,就只支持通过HTTPS访问了
2. AFNetworking3.0 调用例子
2.1
使用如下命令获取https.cer文件
openssl s_client -connect 127.0.0.1:443 </dev/null 2>/dev/null | openssl x509 -outform DER > https.cer
把cer文件放入ios应用的bundle中,然后使用如下代码进行配置
//afnetworking对于自行颁发证书的配置
NSURL *baseURL = [NSURL URLWithString: @"https://127.0.0.1:3000/v1"];
NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"https" ofType:@"cer"];
NSData * certData =[NSData dataWithContentsOfFile:cerPath];
NSSet * certSet = [[NSSet alloc] initWithObjects:certData, nil];
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
[securityPolicy setAllowInvalidCertificates:YES];
[securityPolicy setPinnedCertificates:certSet];
[securityPolicy setValidatesDomainName:NO];
AFHTTPSessionManager * manager = [[AFHTTPSessionManager alloc] initWithBaseURL:baseURL];
manager.securityPolicy = securityPolicy;
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager GET:@"users/avatar" parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject)
NSLog(@"PLIST: %@", responseObject);
failure:^(NSURLSessionTask *operation, NSError *error)
NSMutableData *body = error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey];
NSString* aStr = [[NSString alloc] initWithData:body encoding:NSUTF8StringEncoding];
NSLog(@"%@",aStr);
];
以上是关于afnetworking使用https的主要内容,如果未能解决你的问题,请参考以下文章
使用 Afnetworking 获取 UIImageView 并将其放入数组中
AFNetworking 2.0:是不是可以将纯 json 放入 POST 请求的正文中?