HTTPS POST iOS Synchronous Request

For Android, I was able to send POST requests as follows:

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 execute a synchronous POST request using https on iOS?

+5
source share
1 answer

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 addressed on your server.

And here is from the docs :

errSSLHostNameMismatch -9843 The host name you are associated with does not match any of the host names allowed by the certificate. This is usually caused by the wrong value for the kCFStreamSSLPeerName property in the thread-related dictionary. Key is kCFStreamPropertySSLSettings. Available on OS X version 10.4 and later.

hope this help

+7
source

Source: https://habr.com/ru/post/1200456/


All Articles