處理與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對象的映射。以下列方式
[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請求: - - :
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 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
檢查此鏈接希望它會幫助你http://stackoverflow.com/questions/1973325/nsurlconnection-and-basic-http-身份驗證 – Exploring 2013-03-22 11:14:17
@sanjitshaw我需要POST基於... – 2013-03-22 11:23:05
當你說AFNetworking沒有成功,你是如何使用它,你遇到什麼問題?您的朋友輸入了哪種類型的身份驗證? – 2013-03-22 11:54:11