我是iOS開發新手,在創建簡單的Json POST請求時遇到問題。 我有一個包含用戶和密碼的NSDictionary,我想將這些值作爲Json發送到服務器並獲得響應。我有沒有使用restkit工作,但我無法弄清楚如何使用RestKit完成相同的功能,並且找不到我想要的一個好例子。使用RESTKit做一個簡單的json POST
- (bool) login{
NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
[params setValue:self.email forKey:@"email"];
[params setValue:self.password forKey:@"password"];
NSMutableDictionary* rpcData = [[NSMutableDictionary alloc] init];
[rpcData setValue:@"2.0" forKey:@"jsonrpc"];
[rpcData setValue:@"authenticate" forKey:@"method"];
[rpcData setValue:@"" forKey:@"id"];
[rpcData setValue:params forKey:@"params"];
[[RKClient sharedClient] post:@"/api/rpc/" params:rpcData delegate:self];
return nil;
}
服務器期待一個JSON這樣的:
{
jsonrpc : '2.0',
method : 'authenticate', // method name goes here
params : { // params are method-specific
email : '[email protected]',
password : 'secret'
},
id : 2 // The id can be anything, it will be sent back with the response
}
我明白,有一個JSON解析器包括RestKit但我無法找到如何分析我的rpcData字典任何文件,我需要使用外部庫嗎?
現在與服務器的通信沒問題,但我沒有發送預期的內容。我的字典以「key = value?key2 = value2 ...」的方式映射。這非常愚蠢的問題,但我被困住了。
更新
通過我寫這篇文章的時候,它的工作,但Restkit已經更新,所以我不知道這是否會工作,請查看他們的文檔
下面是解對於我的問題,當我需要調用服務時,我所做的是理想的使用RPC API:
1.-首先在您的對象中需要導入Restkit和RKRequestSerialization,這非常重要:
#import <RestKit/RestKit.h>
#import <RestKit/RKRequestSerialization.h>
@interface myObject : NSObject <RKRequestDelegate,RKObjectLoaderDelegate>
2:這裏是登錄功能發送的帖子:
- (void) login:(NSString *)username :(NSString *)password{
RKClient *myClient = [RKClient sharedClient];
NSMutableDictionary *rpcData = [[NSMutableDictionary alloc] init ];
NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
//User and password params
[params setObject:password forKey:@"password"];
[params setObject:username forKey:@"email"];
//The server ask me for this format, so I set it here:
[rpcData setObject:@"2.0" forKey:@"jsonrpc"];
[rpcData setObject:@"authenticate" forKey:@"method"];
[rpcData setObject:@"" forKey:@"id"];
[rpcData setObject:params forKey:@"params"];
//Parsing rpcData to JSON!
id<RKParser> parser = [[RKParserRegistry sharedRegistry] parserForMIMEType:RKMIMETypeJSON];
NSError *error = nil;
NSString *json = [parser stringFromObject:rpcData error:&error];
//If no error we send the post, voila!
if (!error){
[[myClient post:@"/" params:[RKRequestSerialization serializationWithData:[json dataUsingEncoding:NSUTF8StringEncoding] MIMEType:RKMIMETypeJSON] delegate:self] send];
}
}
目前尚不清楚問題是什麼。數據沒有被髮送?沒有收到?你的請求和響應頭文件是什麼樣的?考慮使用http://www.charlesproxy.com/來提供幫助。另外,不要忘記查看以前問題的最佳答案旁邊的綠色複選標記。你會以這種方式獲得更多回應。 – 2012-02-01 19:57:57
以我的代碼的方式,我沒有發送JSON請求。我清楚地知道,服務器獲取的數據類似於「?jsonrpc ='2.0'&method ='authenticate'...」我需要知道如何將其解析爲JSON – clopez 2012-02-01 20:05:31
您可以通過激活在代碼RKLogConfigureByName(「RestKit/Network」,RKLogLevelTrace)中通過這一行調試日誌;' – redDragonzz 2012-03-05 17:31:56