iOS9苹果将原http协议改成了https协议的方法
解决方法:
在info.plist加入key
<key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <true/> </dict>
下面给大家介绍ios中http和https协议的访问
最近做个项目,开始采用的是HTTP协议实现客户端和服务器端的交互,后来需要改成HTTPS协议。在修改的过程中发现了一些问题,解决方案如下:
HTTP:
NSString*urlString=[NSStringstringWithFormat:@"https://127.0.0.1/default.aspx?USER=%@",@"111"]; NSMutableURLRequest*request=[[[NSMutableURLRequestalloc]init]autorelease]; [requestsetURL:[NSURLURLWithString:urlString]]; [requestsetHTTPMethod:@"GET"]; NSHTTPURLResponse*urlResponse=nil; NSError*error=[[NSErroralloc]init]; NSData*responseData=[NSURLConnectionsendSynchronousRequest:requestreturningResponse:&urlResponseerror:&error]; NSMutableString*result=[[NSMutableStringalloc]initWithData:responseDataencoding:NSUTF8StringEncoding]; NSLog(@"Theresultstringis:%@",result);
HTTPS
事件触发
{
NSString*urlString=[NSStringstringWithFormat:@"https://127.0.0.1/default.aspx?USER=%@",@"111"];
NSMutableURLRequest*request=[[NSMutableURLRequestalloc]initWithURL:[NSURLURLWithString:urlString]cachePolicy:NSURLRequestReloadIgnoringLocalCacheDatatimeoutInterval:5];
//设置请求方式为get
[requestsetHTTPMethod:@"GET"];
//添加用户会话id
[requestaddValue:@"text/html"forHTTPHeaderField:@"Content-Type"];
//连接发送请求
finished=false;
NSURLConnection*conn=[[NSURLConnectionalloc]initWithRequest:requestdelegate:self];
//堵塞线程,等待结束
while(!finished){
[[NSRunLoopcurrentRunLoop]runMode:NSDefaultRunLoopModebeforeDate:[NSDatedistantFuture]];
}
}
-(void)connection:(NSURLConnection*)connectiondidReceiveResponse:(NSURLResponse*)response
{}
-(void)connectionDidFinishLoading:(NSURLConnection*)connection
{
//[_waitingDialogdismissWithClickedButtonIndex:0animated:NO];
[connectionrelease];
}
-(void)connection:(NSURLConnection*)connectiondidFailWithError:(NSError*)error
{
}
-(BOOL)connectionShouldUseCredentialStorage:(NSURLConnection*)connection{
returnNO;
}
//下面两段是重点,要服务器端单项HTTPS验证,iOS客户端忽略证书验证。
-(BOOL)connection:(NSURLConnection*)connectioncanAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace*)protectionSpace{
return[protectionSpace.authenticationMethodisEqualToString:NSURLAuthenticationMethodServerTrust];
}
-(void)connection:(NSURLConnection*)connectiondidReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge*)challenge{
NSLog(@"didReceiveAuthenticationChallenge%@%zd",[[challengeprotectionSpace]authenticationMethod],(ssize_t)[challengepreviousFailureCount]);
if([challenge.protectionSpace.authenticationMethodisEqualToString:NSURLAuthenticationMethodServerTrust]){
[[challengesender]useCredential:[NSURLCredentialcredentialForTrust:challenge.protectionSpace.serverTrust]forAuthenticationChallenge:challenge];
[[challengesender]continueWithoutCredentialForAuthenticationChallenge:challenge];
}
}
NSLog(@"getthewholeresponse");
//[receivedDatasetLength:0];
}
//处理数据
-(void)connection:(NSURLConnection*)connectiondidReceiveData:(NSData*)data
{
}