0

I tried to add an entry to db using a POST request in Objectve-C. My service is:

@RequestMapping(method = RequestMethod.POST, headers = "content-type=application/json")
public
@ResponseBody
boolean addEmployee(@ModelAttribute User user) {
    try {
        logger.log(Level.INFO, user.getCountry());
        userDataService.addUser(user);

        return true;
        //return new Status(1, "Employee added Successfully !");
    } catch (Exception e) {
        e.printStackTrace();
        return false;//new Status(0, e.toString());
    }

}

When I try this on Postman, it's working fine with x-www-form-urlencoded. But when I try this in Objective-C, nothing happens. Here is what I tried:

NSString *jsonInputString = @"{\"userName\":\"abcd\"}";

NSString *jsonRequest = jsonInputString;

NSLog(@"jsonRequest is %@", jsonRequest);

NSURL *url = [NSURL URLWithString:@"http://localhost:8080/user"];

NSOperationQueue *queue = [[NSOperationQueue alloc] init];

NSMutableURLRequest *rq = [NSMutableURLRequest requestWithURL:url];
[rq setHTTPMethod:@"POST"];

NSData *jsonData = [jsonInputString dataUsingEncoding:NSUTF8StringEncoding];
[rq setHTTPBody:jsonData];

[rq setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[rq setValue:[NSString stringWithFormat:@"%ld", (long)[jsonData length]] forHTTPHeaderField:@"Content-Length"];

[NSURLConnection sendAsynchronousRequest:rq queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
    NSLog(@"%@", [error localizedDescription]);
}];

In completion block, the log prints "Could not connect to the server". How can I call the service with JSON data?

3
  • Given that the this client code looks to be in good shape, most of the things that can go wrong are on the connection-server side. Can you get this working in CURL and post that CURL here? (consider using [NSOperationQueue mainQueue] as the queue parameter). Commented Mar 7, 2015 at 20:57
  • 1
    I would take the log message as meaning that no one is listening on localhost:8080 ... It's way before the json is sent or even processed server-side. Commented Mar 7, 2015 at 21:02
  • Oh. I figure out the problem. I run this using iPhone. in that case localhost means iPhone's localhost. Any way to resolve it Commented Mar 7, 2015 at 21:21

1 Answer 1

1
Something like this should work

// 1: Create your URL, Session config and Session

NSString *jsonInputString = @"{\"userName\":\"abcd\"}";

NSString *jsonRequest = jsonInputString;

NSURL *url = [NSURL URLWithString:@"http://localhost:8080/user"];

  NSURLSessionConfiguration *config =
      [NSURLSessionConfiguration defaultSessionConfiguration];
  NSURLSession *session = [NSURLSession sessionWithConfiguration:config];

  // 2: Create NSMutableRequest object
  NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
  request.HTTPMethod = @"POST";

  // 3: Create Jsondata object
  NSError *error = nil;
 NSData *jsonData = [jsonInputString dataUsingEncoding:NSUTF8StringEncoding];

  // Asynchronously Api is hit here
  NSURLSessionUploadTask *dataTask =
      [session uploadTaskWithRequest:request
                            fromData:data
                   completionHandler:^(NSData *data, NSURLResponse *response,
                                       NSError *error) {

                       NSLog(@"%@", data);

                       NSDictionary *json =
                           [NSJSONSerialization JSONObjectWithData:data
                                                           options:0
                                                             error:nil];
                       NSLog(@"%@", json);
                       success(json);
                   }];

  [dataTask resume]; // Executed First
Sign up to request clarification or add additional context in comments.

Comments

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.