0

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.

7
  • Try adding the Content-Length header... Commented Nov 24, 2011 at 0:33
  • I believe, I do have the Content-Length code, it is the last line with starts with [request ... Commented Nov 24, 2011 at 0:39
  • You may also want to try with application/x-www-form-urlencoded for the content type. Commented Nov 24, 2011 at 0:43
  • And I don't think the Accept header is needed... Commented Nov 24, 2011 at 0:44
  • Hello Macmade, I did try the application/x-www-from-urlencoded, and unfortunately it did not work for me. Thanks for the suggestion. Commented Nov 24, 2011 at 0:50

1 Answer 1

2

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];
Sign up to request clarification or add additional context in comments.

1 Comment

forgot the following line of code, right before the startAsynchronous [request setPostValue:@"submit" forKey:@"post"]; [request startAsynchronous];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.