5

我正在编写一个 iPhone 应用程序,我想连接到“HTTPS”服务器以获取一些信息。但是,我在控制台中收到错误消息

NSUnderlyingError = 错误域=kCFErrorDomainCFNetwork 代码=-1202 UserInfo=0x3e95cf0 "此服务器的证书无效。您可能正在连接一个伪装成“example.com”的服务器,这可能会使您的机密信息面临风险。"; }

如何信任证书并获取 http 状态码 200

以下是我的代码。

    NSMutableURLRequest *request_get2 = [[[NSMutableURLRequest alloc] init] autorelease];
    [request_get2 setURL:[NSURL URLWithString:@"https://www.example.com"]]; 
    [request_get2 setHTTPMethod:@"GET"];
    [request_get2 setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    //[request_get2 setValue:@"text/html; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
    [request_get2 setValue:@"https://www.example.com" forHTTPHeaderField:@"Referer"];
    [request_get2 setHTTPShouldHandleCookies:YES];
    // cookiesString is in format "cookieName=cookieValue;"
    [request_get2 setValue: (NSString *) cookiesString forHTTPHeaderField:@"Cookie"];


    // doGet - response
    NSHTTPURLResponse *response_get2 = nil;  // it change from 'NSURLRespaonse' to 'NSHTTPURLResponse'
    NSError *error_get2 = nil;
    NSData *responseData_get2 = [NSURLConnection sendSynchronousRequest:request_get2 returningResponse:&response_get2 error:&error_get2];
    NSString *data_get2 = [[NSString alloc]initWithData:responseData_get2 encoding:NSUTF8StringEncoding];

    if (!error_get2) {
        NSString *responseURL_get2 = [[response_get2 URL] absoluteString];           // null value
        NSString *responseTextEncodingName_get2 = [response_get2 textEncodingName];  // null value
        NSString *responseMIMEType_get2 = [response_get2 MIMEType];                  // null value
        NSUInteger *responseStatusCode_get2 = [response_get2 statusCode]; //[responseStatusCode intValue]; // the status code is 0
    }
    else {
        NSLog(@"\nsomething went wrong: %@\n", [error_get2 userInfo]); // got the error in here
    }
4

2 回答 2

11

I think that adding an untrusted certificate is (at least in the simulator) not possible, but you can tell your NSURLConnection Delegate to accept self signed certificates (or generally untrusted ones)

The following link helped me solve the issue!

How to use NSURLConnection to connect with SSL for an untrusted cert?

于 2010-07-05T12:08:00.973 回答
0

信任所有证书是一个非常糟糕的主意。恶意人员可以对您的用户执行中间人攻击,以读取或更改所有传输的数据。

我相信您的证书不包含验证系统可信根证书路径所需的所有中间证书。某些 SSL 配置验证工具可能会将其报告为不完整的证书链

您可以通过将证书中的所有证书连接到受信任的根证书(不包括,按此顺序)手动解决证书链不完整问题,以防止此类问题。请注意,受信任的根证书不应该存在,因为它已经包含在系统的根证书存储中。

您应该能够从颁发者那里获取中间证书并自己将它们连接在一起。我编写了一个脚本来自动化该过程,它需要一个证书来生成正确链接的证书的输出。https://github.com/zakjan/cert-chain-resolver

于 2015-01-19T05:25:45.097 回答