NSURLConnection and empty message variables

I am at my end with this because I have used very similar code in the past and it worked perfectly.

The following code results in empty variables $_POST

on the server. I verified this with:

file_put_contents('log_file_name', "log: ".$word, FILE_APPEND);

      

the only content log_file_name

was "log:"

Then I tested PHP with a simple HTML form. It performed as expected.

Objective-C:

    NSString *word = @"this_word_gets_lost";
    NSString *myRequestString =  [NSString stringWithFormat:@"word=%@",
                                  word];

    [self postAsynchronousPHPRequest:myRequestString toPage:@"http://www.mysite.com/pagefolder/mypage.php" delegate:nil];
}

-(void) postAsynchronousPHPRequest:(NSString*)request toPage:(NSString*)URL delegate:(id)delegate{
    NSData *requestData = [ NSData dataWithBytes: [ request UTF8String ] length: [ request length ] ];
    NSMutableURLRequest *URLrequest = [ [ NSMutableURLRequest alloc ] initWithURL: [ NSURL URLWithString: URL ] ]; 
    [ URLrequest setHTTPMethod: @"POST" ];
    [ URLrequest setHTTPBody: requestData ];

    [ NSURLConnection connectionWithRequest:URLrequest delegate:delegate];
    [URLrequest release];
}

      

PHP:

$word = $_POST['word'];
file_put_contents('log_file_name', "log: ".$word, FILE_APPEND);

      

What am I doing wrong in Objective-C that will cause the variable to $_POST

be empty on the server?

+2


a source to share


2 answers


If your code is direct copy, you lose the character @

after NSString *word

. If that's not a problem, it might be NSData *requestData = [ NSData dataWithBytes: [ request UTF8String ] length: [ request length ] ];

. Try this instead:

NSData *requestData = [request dataUsingEncoding:NSUTF8StringEncoding];  

      



EDIT: I'm not an HTTP expert, but I think redirects usually kill POST data as the data goes directly to the server (see here ) - IE seems to automatically retransmit POSTs sometimes, but is not part of the HTTP specification.

+2


a source


Okay, now I'm really dumb. I found the problem.

On my site, the actual url is: http://www.mysite.com/PageFolder/mypage.php

which has a redirect step so that all requests for documents inside are http://www.mysite.com/PageFolder/mypage.php

redirected to PageFolder

.



when I changed the url in my Objective-C code to not use the redirect page, my post variables work fine.

I will revoke my consent to this anwser and give credit to anyone who can explain why a redirect might kill post data.

+2


a source







All Articles