Thursday, July 24, 2014

Invoke RESTful web-service

//Prepare a JSON based on user input
NSData *postData = [[NSString stringWithFormat:@"{\"EmailAddress\":\"%@\",\"Password\":\"%@\"}",txtLogin,txtPassword] dataUsingEncoding:NSUTF8StringEncoding];


NSURL *url = [NSURL URLWithString:strLoginURL]; 

//Create a request with timeout interval
 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
            cachePolicy:NSURLRequestReloadIgnoringLocalCacheData  timeoutInterval:180.0];
        
 [request setHTTPMethod:@"POST"]; // Set method type as POST/GET
 [request setHTTPBody:postData];

 NSString *postDataLengthString = [[NSString alloc] initWithFormat:@"%d", [postData length]];

 [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
 [request setValue:postDataLengthString forHTTPHeaderField:@"Content-Length"];

  NSURLResponse *response = NULL;
  NSError *requestError = NULL;

// Send Synchronous request. Preferred for small amount of response
  NSData *responseData = [NSURLConnection sendSynchronousRequest:request  returningResponse:&response error:&requestError];

 jsonDeserializer = [CJSONDeserializer deserializer];
  NSError *error=nil;

//Fetch result dictionary from response
  NSMutableDictionary  *resultsDictionary = [[NSMutableDictionary alloc]
      initWithDictionary:[jsonDeserializer deserializeAsDictionary:responseData error:&error]];

  NSLog(@"Result : %@",[resultsDictionary description]);


No comments:

Post a Comment