使用RESTKit发出POST请求

时间:2013-02-14 16:20:31

标签: ios objective-c post restkit

我正在尝试使用restKit发出POST请求,但我不能。

我的代码是这样的:

    NSString *urlAddTask;
    urlAddTask = [NSString stringWithFormat:@"some URL"];

    RKObjectManager* mgr = [RKObjectManager sharedManager];

    mgr.serializationMIMEType = RKMIMETypeJSON;

    RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]];
    [mapping mapKeyPath: @"name"       toAttribute:@"name"         ];

    RKObjectMapping* mappingForSerialization = [mapping inverseMapping];

    [mgr.mappingProvider setSerializationMapping:mappingForSerialization forClass:[NSManagedObject class]];

    [mgr.router routeClass:[NSManagedObject class] toResourcePath:urlAddTask forMethod:RKRequestMethodPOST];

    Task *t=[[Task alloc]init];
    t.name=@"One name";

    [[RKObjectManager sharedManager].router routeClass:[Task class] toResourcePath:@"/tasks" forMethod:RKRequestMethodPOST];

    [mgr postObject:t delegate:nil/*self*/];

当我执行此代码时,我收到此错误:

    *** Assertion failure in -[RKObjectLoader prepareURLRequest], /myAppRoute/Libraries/RestKit/Code/ObjectMapping/RKObjectLoader.m:304
2013-02-14 17:12:25.202 Aplication[1929:c07] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'You must provide a serialization mapping for objects of type 'Task''

我认为我做了很多坏事。我正在寻找一个关于如何发布POST的好例子,但我找不到任何可以帮助我做出请求的帖子。

你能帮我解决一下我的代码o给我一个关于如何做到这一点的好例子吗?

谢谢!


更新

我像你说的那样更新了序列化行。然后我有这个错误:

2013-02-15 10:16:45.009 myApp[829:c07] W restkit.network:RKObjectLoader.m:241 Unable to find parser for MIME Type 'text/html'
2013-02-15 10:16:45.009 myApp[829:c07] W restkit.network:RKObjectLoader.m:262 Encountered unexpected response with status code: 200 (MIME Type: text/html)

然后我尝试用此行将serializationMIMEType从RKMIMETypeJSON更改为RKMIMETypeXML:

mgr.serializationMIMEType = RKMIMETypeXML;

现在错误是这样的:

2013-02-15 10:20:01.315 myApp[873:c07] -[RKXMLParserLibXML stringFromObject:error:]: unrecognized selector sent to instance 0x86ae910
2013-02-15 10:20:01.316 myApp[873:c07] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[RKXMLParserLibXML stringFromObject:error:]: unrecognized selector sent to instance 0x86ae910'

我怎么说我敢肯定我做了很多坏事。我很失落。

谢谢!

2 个答案:

答案 0 :(得分:1)

我无法谈论其他错误,但正如异常消息所示,Task类缺少序列化映射。你应该改变

[mgr.mappingProvider setSerializationMapping:mappingForSerialization forClass:[NSManagedObject class]];

[mgr.mappingProvider setSerializationMapping:mappingForSerialization forClass:[Task class]];

答案 1 :(得分:1)

好吧,你的代码似乎有些乱,有些事情是错的。

// Set url of webservice
NSURL *taskURL = [NSURL URLWithString:@"http://demopath.com"];   

// Set object manager with base url
RKObjectManager *objectManager = [[RKObjectManager alloc] init];
objectManager = [RKObjectManager managerWithBaseURL:taskURL];

// Set accepted data type
[objectManager setSerializationMIMEType:@"application/json"];
[objectManager setAcceptMIMEType:@"application/json"];
// [objectManager.client setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; // Optional

// Set store 
RKManagedObjectStore* objectStore = [RKManagedObjectStore objectStoreWithStoreFilename:@"yourFileName.xml"];
objectManager.objectStore = objectStore;

// Set route
[objectManager.router routeClass:[Task class] toResourcePath:@"/tasks" forMethod:RKRequestMethodPOST]; // Set path for posting objects

// Set mapping
RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[Task class]];
[mapping mapKeyKath:@"nameServer" toAttribute:@"nameClient"]; // If webservice and local attributes got different names, first is the receiving one, second the local one

// Init your new object
Task *task = [Task new];
task.nameClient = @"Hello world";

// Send post request to webservice
[objectManager.mappingProvider setSerializationMapping:[mapping inverseMapping] forClass:[Task class]]; // Set inverse mapping on post reques   
[objectManager postObject:task usingBlock:^(RKObjectLoader *loader)
 {
     loader.backgroundPolicy = RKRequestBackgroundPolicyContinue; // Continues request when app is moving to background
     // loader.resourcePath = @"/tasks"; // // Optional, because it has been configured in the routing
     // loader.objectMapping = [objectManager.mappingProvider objectMappingForClass:[Task class]]; // Optional, because it has been configured before
     loader.delegate = self;

     loader.onDidLoadObjects = ^(NSArray *objects) {
      NSLog(@"It Worked: %@", objects);
  };
     loader.onDidFailWithError = ^(NSError *error) {
      NSLog(@"It Failed: %@", error);
  };
 }];

当您的Web服务返回200且MIME类型text/html时,您似乎尝试调用需要授权的Web服务(因为Web服务返回登录页面)。如果您需要授权请求,请在发布请求之前添加以下方法。

// Set authorization
objectManager.client.username = @"yourUsername";
objectManager.client.password = @"yourPassword";
objectManager.client.authenticationType = RKRequestAuthenticationTypeHTTPBasic; // Change like you need it

希望你能把事情搞定。