Search code examples
phpjsonpostxcode4nsmutableurlrequest

Post json using Xcode


I am trying to send data, in json format to my webservice, using POST. I have a php page on my server that receives the json string and prints it out.

The issue is, that the POST array recieved is empty, below is my code on my application:

NSString *jsonRequest = @"{\"username\":\"james\",\"password\":\"james1234\"}";
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
NSURL *url = [NSURL URLWithString:[[NSString alloc] initWithFormat:@"http://mydomain.com/check.php"]];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];

[request setHTTPMethod:@"POST"];
[request setHTTPBody:requestData];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d",[requestData length]] forHTTPHeaderField:@"Content-Length"];

[NSURLConnection connectionWithRequest:[request autorelease] delegate:self];

The check.php has the following code:

<?php

    print_r($_POST);
?>

I am getting the following output: Array( )

I have tried everything, and cannot seem to get the json string sent to my webservice. I am sure, I am missing something, however I do not know what it is.


Solution

  • I got it to work, I had to use the ASIHTTP library. below is the code:

    NSURL *url = [NSURL URLWithString:[[NSString alloc] initWithFormat:@"http://mydomain.com/check.php"]];
    
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    [request setRequestMethod:@"POST"];
    [request setDelegate:self];
    [request setPostValue:@"james" forKey:@"username"];
    [request setPostValue:@"james1234" forKey:@"password"];
    [request startAsynchronous];