NSString *username = @"username";
NSString *password = @"password";
NSURL *loginurl = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.reddit.com/api/login/%@",username]];
NSMutableURLRequest *loginrequest = [NSMutableURLRequest requestWithURL:loginurl];
[loginrequest setHTTPMethod:@"POST"];
NSData *loginRequestBody = [[NSString stringWithFormat:@"api_type=json&user=%@&passwd=%@",username,password] dataUsingEncoding:NSUTF8StringEncoding];
[loginrequest setHTTPBody:loginRequestBody];
NSURLResponse *loginResponse = NULL;
NSError *loginRequestError = NULL;
NSData *loginResponseData = [NSURLConnection sendSynchronousRequest:loginrequest returningResponse:&loginResponse error:&loginRequestError];
NSString *loginResponseString = [[NSString alloc]initWithData:loginResponseData encoding:NSUTF8StringEncoding];
NSLog(@"%@",loginResponseString);
NSLog打印出这个:(替换了一些字母)
{" json":{"错误":[],"数据":{" modhash": " j5hq16ukw2f17a9c153xxxxxxxxxa72ad989c96c904d49a97e"," cookie": " 13986184,2012-07-14T12:41:05,349f968b3089af75978xxxxxxxxxxxx761397ba0"}}}
如何访问modhash和cookie?我试过了
[loginResponseData valueForKey:@"json"];
但它表示该类不是密钥json的密钥值编码
答案 0 :(得分:0)
loginResponseString是一个NSString - 它不知道里面是否有JSON。您必须将此JSON解析为NSDictionary,然后您可以使用其方法来检索响应数据。试试我的JSON解析器:http://github.com/H2CO3/CarbonateJSON
使用我的CarbonateJSON库的示例:
NSDictionary *parsedResponse = [loginResponseString parseJson];
NSString *modhash = [[[parsedResponse objectForKey:@"json"] objectForKey:@"data"] objectForKey:@"modhash"];
答案 1 :(得分:0)
对于在我之后看到这个的人,你可以查看H2CO3的解决方案,但我发现最简单的解决方案是使用NSJSONSerialization以支持的方式完成。
NSError *error;
NSData *jsonData = [loginResponseString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *loginResults = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSString *modhash = [[[loginResults valueForKey:@"json"] valueForKey:@"data"]valueForKey:@"modhash"];
为我工作。