2

Hee,

I got a problem with my NSURLRequest HTTP POST and i cannot find out what is going wrong.

This is my server side php:

<html>
<head>
</head>
<body>
    <?php 
        if (! isset($_POST['sometext'])) {
            echo "NOT SET";
        } else {
            echo $_POST['sometext'];
        }
    ?>
</body></html>

This is my Objective c code to post the data:

NSString *urlString = @"http://localhost:8888/postpage";
NSURL *url = [[NSURL alloc] initWithString:urlString];
NSMutableURLRequest *urlRequest=[NSMutableURLRequest requestWithURL:url];

[url release];


    [urlRequest setHTTPMethod:@"POST"];
    [urlRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
    [urlRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
    NSString *postString = @"sometext=Hello&language=en";
    NSString *msgLength = [NSString stringWithFormat:@"%d", [postString length]];
    [urlRequest setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];


NSString *returnString = [[NSString alloc] initWithData:[NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:nil] encoding:NSUTF8StringEncoding];
NSLog(@"%@",returnString);

The result of the NSLog is:

<html>
    <head>
    </head>
    <body>
        NOT SET 
    </body>
</html>

Thanks already

Mats Stijlaart
  • 5,058
  • 7
  • 42
  • 58

3 Answers3

4

I came across the same problem some times, and the solution was to add this to the request:

[urlRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
Ludovic Landry
  • 11,606
  • 10
  • 48
  • 80
2

A possible source of the problem may be the fact that in the code you are setting the Content-Length header before assigning the value to the msgLength variable. Because ob Obj-C methods on the nil object return nil (and nil is 0), you are setting the Content-Lenght to 0. Try Moving the line

NSString *msgLength = [NSString stringWithFormat:@"%d", [postString length]];

before

[urlRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
fsaint
  • 8,759
  • 3
  • 36
  • 48
0

I suggest you can try ASIHTTPRequest Library that it not only can easy handle http request like your problem just use ASIFormDataRequest, but also easy to asynchronous handle.

Daniel
  • 324
  • 3
  • 10
  • 1
    BSD licensed, free to use, non invasive, so can be used in commercial projects without giving up rights to source code. – MCannon Mar 21 '11 at 14:37