RestKit POST请求出错

时间:2013-10-07 10:51:47

标签: ios nsurlrequest restkit-0.20

我正在尝试使用RestKit将POST请求中的JSON数据发送到服务器但是我收到错误

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

我写的代码是:

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];

有人可以帮我弄清楚究竟是什么问题? 我也试过设置内容类型如下:

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

2 个答案:

答案 0 :(得分:1)

试试这个

RKObjectManager *objectManager = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:BASE_URL]];
[objectManager setRequestSerializationMIMEType:RKMIMETypeJSON];

答案 1 :(得分:0)

您必须注册 RKNSJSONSerialization 类。请在您的方法中包含以下代码。

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