同步HTTPS POST请求iOS

时间:2014-08-15 22:35:33

标签: ios objective-c post ssl https

对于Android,我已经能够通过以下方式发送POST请求:

HttpClient http = new DefaultHttpClient();
HttpPost request = new HttpPost("https://somewebsite.com");
request.setEntity(new StringEntity(data));
http.execute(request);

但是,在iOS上我收到以下错误:

NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9843)

在iOS上使用https执行同步POST请求的最佳方法是什么?

1 个答案:

答案 0 :(得分:8)

您可以尝试此功能:

-(NSData *)post:(NSString *)postString url:(NSString*)urlString{

    //Response data object
    NSData *returnData = [[NSData alloc]init];

    //Build the Request
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[postString length]] forHTTPHeaderField:@"Content-length"];
    [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];

    //Send the Request
    returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];

    //Get the Result of Request
    NSString *response = [[NSString alloc] initWithBytes:[returnData bytes] length:[returnData length] encoding:NSUTF8StringEncoding];

    bool debug = YES;

    if (debug && response) {
        NSLog(@"Response >>>> %@",response);
    }


    return returnData;
}

以下是您使用它的方式:

NSString *postString = [NSString stringWithFormat:@"param=%@",param];
NSString *urlString = @"https://www.yourapi.com";

NSData *returnData =  [self post:postString url:urlString];

编辑:

我在源代码中找到了错误代码:

errSSLHostNameMismatch = -9843, /* peer host name mismatch */

问题应该在您的服务器上解决。

这是来自docs

  

errSSLHostNameMismatch -9843 您关联的主机名确实   不匹配证书允许的任何主机名。这是   通常由kCFStreamSSLPeerName的值不正确引起   与流相关的字典中的属性   kCFStreamPropertySSLSettings键。适用于OS X v10.4及更高版本。

希望这个帮助