IPhone : Post json array to web service not working

on Tuesday, February 24, 2015

I'm using a dictionary to create a few json objects.



NSDictionary *dict = @{@"cpu" : self.proData ,
@"date" : timeMilliString,
@"memory" : self.memData
};

self.jsonObj1 = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
self.jsonObj2 = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
self.jsonObj3 = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];


Then I'm using putting these objects into an array.



NSArray *jsonArray = @[self.jsonObj1, self.jsonObj2, self.jsonObj3];


What is the best way to post this NSArray to my web service?


I have tried the following method but it does not work (returns an error)



NSData* responseData = nil;
NSString *urlString = @"http://10.2.176.100:9000/TestIOS?";
NSURL *url=[NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
responseData = [NSMutableData data] ;
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
NSString *bodydata=[NSString stringWithFormat:@"%@",self.jsonArray];

[request setHTTPMethod:@"POST"];
NSData *req=[NSData dataWithBytes:[bodydata UTF8String] length:[bodydata length]];
[request setHTTPBody:req];
NSURLResponse* response;
NSError* error = nil;
responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

NSLog(@"the final output is:%@",responseString);


Edit: I'm using Postman to test my web service and it works as follows: http://10.2.176.100:9000/TestIOS?mobileData


The url is followed by mobileData which is the name of the json object array.


Edit 2: The error : {"timestamp":1424764929646,"status":400,"error":"Bad Request","exception":"org.springframework.web.bind.MissingServletRequestParameterException","message":"Required String parameter 'mobileData' is not present","path":"/TestIOS"} Thanks.


0 comments:

Post a Comment