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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With