27

I am trying to post data to a PHP web service.
I am familiar doing this in html using query $.post but I am very much stumped trying this in objective C. I tried several blogs & questions found on stackoverflow.

I finally came up with the following code:

NSString *jsonRequest = [NSString stringWithFormat:@"{\"Email\":\"%@\",\"FirstName\":\"%@\"}",user,fname];
NSLog(@"Request: %@", jsonRequest);

NSURL *url = [NSURL URLWithString:@"http:myurl..."];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];

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

NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];

I also tried:
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

My web service creates a new user on post and returns the userID. Both successfully make the web service call(a new userID is created), however they do not post the data, i.e. a blank user is created every time.
Please tell me if I am missing anything.

Thanks.

My other attempts:

NSMutableURLRequest *request = 
[[NSMutableURLRequest alloc] initWithURL:
 [NSURL URLWithString:@"myUrl.. "]];

[request setHTTPMethod:@"POST"];

NSString *postString = @"Email=me@test.com&FirstName=Test";

[request setValue:[NSString 
                   stringWithFormat:@"%d", [postString length]] 
forHTTPHeaderField:@"Content-length"];

[request setHTTPBody:[postString 
                      dataUsingEncoding:NSUTF8StringEncoding]];

[[NSURLConnection alloc] 
 initWithRequest:request delegate:self];

I finally solved the issue: FInally, figured out what was wrong. I was using http://mypath?params=123 as my url. I did not gig the complete url(never needed it in other languages). But here I needed to give htt://mypath/index.php?params=123

Praneeta
  • 1,554
  • 3
  • 19
  • 20
  • is your server working correctly? – Inder Kumar Rathore Mar 27 '12 at 03:49
  • yes very much.. As i mentioned in my question, I do this very successfully using jquery. Also, in this case using Objective C the server responds with a userID, just does not accept the data that I posted. – Praneeta Mar 27 '12 at 03:50
  • If I create a dictionary like NSMutableDictionary *parms = [NSMutableDictionary dictionary]; [parms setObject:[email text] forKey:@"Email"]; [parms setObject:[firstname text] forKey:@"FirstName"]; [parms setObject:[lastname text] forKey:@"LastName"]; would there be a way to convert it to NSData & post it? Would that work better instead of posting JSON string? – Praneeta Mar 27 '12 at 04:23
  • @Praneeta : Pls post your solution as answer.. its working perfectly with me too :) thanks – Fahim Parkar Jan 29 '14 at 14:21

4 Answers4

42

I think you would be better off using the NSJSONSerialization class like this:

NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
                     email, @"Email",
                     fname, @"FirstName",
                     nil];
NSError *error;
NSData *postdata = [NSJSONSerialization dataWithJSONObject:tmp options:0 error:&error];
[request setHTTPBody:postData];

Using a dictionary and then converting it to JSON it's easier than creating it like a string.

Good luck!

[SWIFT 3.0] (update)

let tmp = ["email": email,
           "FirstName": fname]
let postData = try? JSONSerialization.data(withJSONObject: tmp, options: .prettyPrinted)
request.httpBody = postData
Zalykr
  • 1,524
  • 1
  • 10
  • 20
  • Thanks , figured out what was wrong. I was using http://mypath?params=123 as my url. I did not gig the complete url(never needed it in other languages). But here I needed to give htt://mypath/index.php?params=123 – Praneeta Mar 27 '12 at 12:01
  • Thanks.but is there any way we can generate the 'tmp' dictionary simply, in a complex json object. generate the correspond dict is bored..ex:{"user":{"id":"18888888888","pass":"12345678",...},"animal":{"code":{"id":1,"code":123456},"key":true}} to generate the dict making me bored. – frank Mar 29 '14 at 04:29
  • 4
    Wasn´t working for me until added header: `[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];` – danielrosero Feb 15 '16 at 19:51
  • Thanks for the suggestion. saved me a lot of time. – shaikh Jun 02 '16 at 06:54
3

I have run your code, and server side receive all message.

POST / HTTP/1.1
Host: linux-test
User-Agent: demoTest/1.0 CFNetwork/548.1.4 Darwin/11.3.0
Content-Length: 44
Accept: application/json
Content-Type: application/json
Accept-Language: en
Accept-Encoding: gzip, deflate
Connection: keep-alive

{"Email":"test@test.com","FirstName":"test"}

And follow code, if jsonRequest has Non-ASCII characters, the [jsonRequest length] will be wrong.

NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];

You can use strlen instead.

NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:strlen([jsonRequest UTF8String])];

or

[jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
xda1001
  • 2,449
  • 16
  • 18
  • well for some reason my server side code does not like my posted data, I'll look into this tomorrow. Thanks for confirming that my code posts data. – Praneeta Mar 27 '12 at 04:29
  • **if the JSON has Non-ASCII charactersthe [jsonRequest length] will be wrong.** - yeah, that is a big gotcha! thanks for the info - I have just spent 2 days debugging a bad request.. all looked fine from the ipad where I was getting the raw JSOn , then posting the service using a different client that all worked... JSOn looked great, had to use wireshark to see the actual data being received at the WS was being cut short – James Dawson Jan 23 '15 at 09:51
  • @looyao I tried both options you gave still i'm setting same error. Can you please help me some idea. Data i'm trying to send is {"prefferedName":"eivFEGX5pXWBGoqNNtF3og==","nameOnCard":"eivFEGX5pXWBGoqNNtF3og==","macID":"m2/ZIJ5pUB37EnF3tmvdtOnozUeOk+iAM82i2Z0nDEFVsc69vqUXNltN6R2dj7nz","expiryDateMonth":"XAcdf3HTEn3pb2TlWQKHHA==","appVersion":"e6NpxcXU34gHeOyowJbWFQ==","cardNumber":"7qYGPbnqgAMwMJ2GoCEGF4neQanULztzvblT873xj4o="} – Charan Giri Dec 15 '16 at 19:58
0
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:@"%@posts", SeverURL]];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setRequestMethod:@"POST"];
[request addRequestHeader:@"content-type" value:@"application/json"];
[request addRequestHeader:@"User-Agent" value:@"iOS"];

request.allowCompressedResponse = NO;
request.useCookiePersistence = NO;
request.shouldCompressRequestBody = NO;
request.delegate=self;
NSString *json=[[self prepareData] JSONRepresentation];//SBJSON lib, convert a dict to json string
[request appendPostData:[NSMutableData dataWithData:[json dataUsingEncoding:NSUTF8StringEncoding]]];

[request startSynchronous];
Cullen SUN
  • 3,517
  • 3
  • 32
  • 33
  • I had a simular problem with JSON request. I don't know why but adding User-Agent:iOS fixed my problem. – Carmen Sep 11 '13 at 14:50
0

Try this one

NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
Inder Kumar Rathore
  • 39,458
  • 17
  • 135
  • 184