要使用 RestKit 0.20 处理 GET/POST 请求/响应,您可以按照以下顺序:-
首先使用基本服务器 URL 配置 RKObjectManager :-
RKObjectManager *manager = [RKObjectManager managerWithBaseURL:baseUrl];
[manager.HTTPClient setDefaultHeader:@"Accept" value:RKMIMETypeJSON];
manager.requestSerializationMIMEType = @"application/json";
由于 RestKit 总是处理请求和响应的对象,因此您必须创建一个具有您期望响应的所有参数的对象。
@interface AuthenticationRequest : NSObject
@property (nonatomic, copy) NSNumber *userName;
@property (nonatomic, copy) NSString *password;
@end
@interface AuthenticationResponse : NSObject
@property (nonatomic, copy) NSNumber *token;
@property (nonatomic, copy) NSString *expiryDate;
@property (nonatomic, copy) NSString *userId;
@end
然后使用服务器 JSON 响应中的键为本地对象中的实例变量配置请求和响应映射。
注意:仅在 POST 或 PUT 请求的情况下配置请求映射。
RKObjectMapping *requestMapping = [RKObjectMapping mappingForClass:[AuthenticationRequest class]];
[requestMapping addAttributeMappingsFromDictionary:@{
@"userName": @"userName",
@"password" : @"password",
}];
RKObjectMapping *responseMapping = [RKObjectMapping mappingForClass:[AuthenticationResponse class]];
[responseMapping addAttributeMappingsFromDictionary:@{
@"TOKEN": @"token",
@"expiryDate" : @"expiryDate",
@"USERID": @"userId"
}];
然后创建一个响应描述符,该描述符将根据您传递的 pathPattern 值执行服务器 JSON 对象与您的本地对象的映射。
RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:requestMapping objectClass:[AuthenticationResponse class] rootKeyPath:nil]
[manager addRequestDescriptor:requestDescriptor];
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:mapping pathPattern:<rest of the path excluding the baseURL> keyPath:nil statusCodes:nil];
[manager addResponseDescriptor:responseDescriptor];
现在通过以下方式在服务器上执行 GET 请求:-
[manager getObjectsAtPath:(NSString *)<rest of the path excluding the baseURL> parameters:(NSDictionary *)parameters
success:(void (^)(RKObjectRequestOperation *operation, RKMappingResult *mappingResult))success
failure:(void (^)(RKObjectRequestOperation *operation, NSError *error))failure];
或通过以下方式在服务器上执行 POST 请求:-
[manager postObject:AuthenticationRequest
path:<rest of the path excluding the baseURL>
success:(void (^)(RKObjectRequestOperation *operation, RKMappingResult *mappingResult))success
failure:(void (^)(RKObjectRequestOperation *operation, NSError *error))failure];
成功和失败块将保留您对响应的处理。
如需更多帮助,您可以参考来自 RestKit 的以下链接:-
https://github.com/RestKit/RKGist/blob/master/TUTORIAL.md