Synchronous HTTPS POST Request iOS

后端 未结 1 695
长情又很酷
长情又很酷 2021-01-01 01:57

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

HttpClient http = new DefaultHttpClient();
HttpPost request = new HttpPost(\"https:/         


        
相关标签:
1条回答
  • 2021-01-01 02:12

    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

    0 讨论(0)
提交回复
热议问题