2

I have a certain URL "http://dev.mycompany.com" and I need to send some data (in JSON format) to it and get the response.

I can't find my way through the hugeload of documentation and related questions here on SO. I've managed to get the data (without sending any data) with NSURLConnection and it works good, the code I have so far is nearly the same as on https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html and so I don't see any point of posting the code I have.

I can't append some string to my URL as the data I need to send is JSON data. I am sorry if I sound like a noob, but I have very little experience in Obj-C and server communication.

Hku
  • 241
  • 2
  • 10

1 Answers1

4

You should send them as parameter to a post NSUrlRequest

As following:

NSURL *aUrl = [NSURL URLWithString:@"http://dev.mycompany.com"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
                                         cachePolicy:NSURLRequestUseProtocolCachePolicy
                                     timeoutInterval:60.0];
[request setHTTPMethod:@"POST"];
NSString *postString = @"yourVarialbes=yourvalues";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];

NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request 
                                                             delegate:self];
[connection start];

For sending JSON Pelase read How to send json data in the Http request using NSURLRequest

Community
  • 1
  • 1
Omar Abdelhafith
  • 21,163
  • 5
  • 52
  • 56
  • My app crashed (SIGABRT). Log says: *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSURLRequest setHTTPMethod:]: unrecognized selector sent to instance – Hku Jun 02 '12 at 17:50
  • Never mind, my problem was that I tried to initialize a `Mutable` object with its non-mutable counterpart. (In this case: `NSMutableURLRequest`) – Hku Jun 02 '12 at 17:59
  • Sorry i edited the answer :), please dont forget to accept :) – Omar Abdelhafith Jun 02 '12 at 18:00
  • Omar, after banging my head on the wall for another 30 minutes, wondering why the server seemed to ignore my postString, I discovered that you need to call `setHTTPMethod` and `setHTTPBody` before declaring the `connection`. Finally it works as intended! – Hku Jun 02 '12 at 18:45
  • i didnt test it on a live server :S, am glad that now it worked :) sorry for the lost 30 mins :S – Omar Abdelhafith Jun 02 '12 at 18:46