Problem using NSURLRequest to POST data to server

前端 未结 3 374
-上瘾入骨i
-上瘾入骨i 2020-11-30 23:50

I create an NSURLRequest to post my data in the iPhone application to a server to proceed the PHP script. My PHP script is look like this.



        
相关标签:
3条回答
  • 2020-12-01 00:16

    try this

    NSString *name = [[NSString alloc]initWith String: @"Hello World"];     
    NSString *email = [[NSString alloc]initWith String: @"Ohai2u"];     
    NSString *urlString = [NSString stringWithFormat:@"http://somedomain.com/sendMail.php?name=%@&email=%@", 
                               [name stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
                               [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    
        NSURL *url = [[NSURL alloc] initWithString:urlString];
    
        NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    
        NSData *urlData;
        NSURLResponse *response;
        urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:nil];
        [url release];
    

    just dont forget to release the strings

    set the headers in the PHP script

    0 讨论(0)
  • 2020-12-01 00:20

    You should remove the leading & in myRequestString and the problem is likely that the correct content-type header is not being sent. Try adding a call to

    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
    

    You should also not pass nil for error, so you can see what the client thinks is going on.

    Unrelated, but your PHP code is open to SQL injection attacks.

    0 讨论(0)
  • It should be noted that ...

    NSData *data = [NSData dataWithBytes: [myRequestString UTF8String]
                                  length: [myRequestString length]];
    

    ... is very bad and can cause vague errors. With UTF8 there is zero guarantee that the number of bytes in your encoded string is the same as the number of characters in your string.

    So instead, you should simply use:

    NSData *data = [myRequestString dataUsingEncoding: NSUTF8StringEncoding];
    
    0 讨论(0)
提交回复
热议问题