Search code examples
iosnsurlrequestrestkit-0.20

Error with RestKit POST Request


I am trying to send JSON data in POST request to server using RestKit but I am getting error

Expected content type {(
    "application/x-www-form-urlencoded",
    "application/json"
)}, got text/plain

The code I have written is:

NSURL *url=[NSURL URLWithString:[NSString   stringWithFormat:@"%@%@",BASE_SERVICE_URL,TASK_SERVICE_URL]];
RKObjectMapping *mapping=[RKObjectMapping mappingForClass:[LoginData class]];
[mapping addAttributeMappingsFromDictionary:@{@"s":@"status",
                                              @"message":@"message"}];
RKResponseDescriptor *descriptor=[RKResponseDescriptor responseDescriptorWithMapping:mapping method:RKRequestMethodPOST pathPattern:nil keyPath:@"" statusCodes:0];
NSMutableURLRequest *request=[[NSMutableURLRequest alloc]initWithURL:url];
[request setHTTPMethod:@"POST"];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
NSDictionary *dict=@{@"task":@"storeProfile",
                     @"fdate":@"01.01.2013",
                     @"tdate":@"19.08.2013",
                     @"keyword":@"taxi && cab",
                     @"AlertHours":@"120",
                     @"AlertDay":@"0",
                     @"AlertTimeStart":@"12:00",
                     @"AlertTimeEnd":@"18:00",
                     @"topic":@[
                             @{@"tname":@"Politics"},
                             @{@"tname":@"Economy"}
                             ],
                     @"publication":@[
                             @{@"pname":@"Vijay Times Online"},
                             @{@"pname":@"Leisure Opportunities"}
                             ]
                     };
NSError *error=nil;
NSData *jsonData=[NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:&error];
if (error) {
    NSLog(@"%@",error.localizedDescription);
    return;
}
[request setHTTPBody:jsonData];
operation=[[RKObjectRequestOperation alloc]initWithRequest:request responseDescriptors:@[descriptor]];
[operation setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
    LoginData *data=[mappingResult.dictionary objectForKey:@""];
    NSLog(@"%@",data.message);
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
    NSLog(@"ERROR:%@",error.localizedDescription);
}];
[operation start];

Could somebody please help me to figure out what exactly the problem is?? I have tried setting content type as follow also:

[request addValue:@"application/application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];

Solution

  • You have to register the class RKNSJSONSerialization . Please include the below code in your method.

    [RKMIMETypeSerialization registerClass:[RKNSJSONSerialization class] forMIMEType:@"text/plain"];