Mats Stijlaart
Mats Stijlaart

Reputation: 5098

NSURLRequest problem

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

Upvotes: 2

Views: 4617

Answers (3)

fsaint
fsaint

Reputation: 8759

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"];

Upvotes: 2

Daniel
Daniel

Reputation: 324

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.

Upvotes: 0

Ludovic Landry
Ludovic Landry

Reputation: 11784

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"];

Upvotes: 4

Related Questions