objcはセキュリティ認証をスキップし、要求する.httpsアドレス

3267 ワード

objcでセキュリティ認証をスキップし、https形式のアドレスを要求するためのいくつかの方法が収集されている.
1、NSURLRequest方式(未テスト)
// Created by Alexandre Colucci on 23/07/2008.
// Copyright 2008 Alexandre Colucci. All rights reserved.

// Dummy interface to avoid a warning.
@interface NSURLRequest (DummyInterface)
+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString*)host;
+ (void)setAllowsAnyHTTPSCertificate:(BOOL)allow forHost:(NSString*)host;
@end

@implementation MainController

-(IBAction)doSomething:(id)sender
{
	// The URL of the Webserver
	NSURL *myWebserverURL = [NSURL URLWithString:@"https://myWebserver.com/"];
	
	// Create the request
	NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:myWebserverURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0];
	
	// Set the HTTP method.
	[theRequest setHTTPMethod:@"POST"];
	
	// Set useful headers
	[theRequest setValue:@"text/xml" forHTTPHeaderField:@"Accept"];
	[theRequest setValue:@"application/xml" forHTTPHeaderField:@"Content-type"];
	
	// The body
	NSString *theDataString = @"<?xml version=\"1.0\" encoding=\"UTF-8\"?><something></something>";
	NSData *theData = [theDataString dataUsingEncoding:NSUTF8StringEncoding];
	[theRequest setHTTPBody:theData];
	
	// Use the private method setAllowsAnyHTTPSCertificate:forHost:
	// to not validate the HTTPS certificate.
	[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[myWebserverURL host]];
	
	// Create the NSURLConnection and init the request.
	[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
}

2、MKNetworkingKit方式:(テスト合格)
で設定を追加します.
MKNetworkEngine *netEngine = [[MKNetworkEngine alloc] initWithHostName:@"your host name"];
MKNetworkOperation *op = [netEngine operationWithURLString:url params:params httpMethod:@"POST"];
//skip ssl auth
op.shouldContinueWithInvalidCertificate = YES;

shouldContinueWithInvalidCertificateデフォルトNO.
ソースコードは次のとおりです.
/*!
 *  @abstract Boolean variable that states whether the operation should continue if the certificate is invalid.
 *  @property shouldContinueWithInvalidCertificate
 *
 *  @discussion
 * If you set this property to YES, the operation will continue as if the certificate was valid (if you use Server Trust Auth)
 *  The default value is NO. MKNetworkKit will not run an operation with a server that is not trusted.
 */
@property (nonatomic,assign) BOOL shouldContinueWithInvalidCertificate;

3、AFNetworking:(実測していない)
方法1:
httpsの非セキュリティアクセスを許可するマクロ定義を追加
#define AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES

方法2:
AFJSONRequestOperation * op = [AFJSONRequestOperation JSONRequestOperationWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:jsonURL]] success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        DLog(@"%@", JSON);
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        DLog(@"%@", error);
    }];
    op.allowsInvalidSSLCertificate = YES;
    [op start];