同步HTTPS POST请求iOS [英] Synchronous HTTPS POST Request iOS

查看:142
本文介绍了同步HTTPS POST请求iOS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

For Android, I've been able to send POST requests in the following way:

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

然而,在iOS上我收到以下错误:

However, on iOS I get the following error:

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

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

What is the best way to perform a synchronous POST request using https on iOS?

推荐答案

您可以尝试此功能:

-(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;
}

以下是您使用它的方式:

And here is how you use it:

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

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

编辑:

我发现错误源代码中的代码:

I found the error code in the source code:

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

问题应该是您服务器上的地址。

The problem should be address on your server.

这里来自 docs


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

errSSLHostNameMismatch -9843 The host name you connected with does not match any of the host names allowed by the certificate. This is commonly caused by an incorrect value for the kCFStreamSSLPeerName property within the dictionary associated with the stream’s kCFStreamPropertySSLSettings key. Available in OS X v10.4 and later.

希望此帮助

这篇关于同步HTTPS POST请求iOS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆