Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronous HTTPS POST Request iOS

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);

However, on iOS I get the following error:

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

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

like image 544
lrAndroid Avatar asked Aug 15 '14 22:08

lrAndroid


1 Answers

You can try this function:

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

Edit:

I found the error code in the source code:

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

The problem should be address on your server.

And here is from the docs:

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.

hope this help

like image 67
meda Avatar answered Sep 30 '22 04:09

meda