iphone - iPhone 上的 "untrusted server certificate"

标签 iphone objective-c http status

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

NSUnderlyingError = Error Domain=kCFErrorDomainCFNetwork Code=-1202 UserInfo=0x3e95cf0 "The certificate for this server is invalid. You might be connecting to a server that is pretending to be “example.com” which could put your confidential information at risk."; }

如何信任证书并获取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
    }

最佳答案

我认为添加不受信任的证书(至少在模拟器中)是不可能的,但您可以告诉您的 NSURLConnection 委托(delegate)接受自签名证书(或通常不受信任的证书)

以下链接帮助我解决了问题!

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

关于iphone - iPhone 上的 "untrusted server certificate",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3178123/

相关文章:

iphone - 通知图标

ios - 模态转换 - 其中一个 View 似乎正在被释放

objective-c - 弱属性在 dealloc 中设置为 nil 但属性的 ivar 不是 nil

android - 通过 HTTP 表单上传文件,通过 MultipartEntityBuilder,带有进度条

python-2.7 - Python2.7 --重构数据包打印html

iphone - 在 iPhone 上构建 "find nearest"位置感知应用程序的最佳方法是什么?

iphone - 利用 OpenGL 中的核心动画制作动画

iphone - 动画/视频作为启动图像 ios

ios - 将 NSData 转换为 NSString 返回随机字符

php - 使用 PHP 将 Post 数据写入文件