1

我正在尝试在 iOS 中创建一个基本的身份验证系统,该系统将 POST 发送到 Django,并在 Django 端对用户进行身份验证并启动会话。现在我可以通过在 URL 中将值作为数据传递并对其进行身份验证来发送用户信息,但是如何从 Django 响应中检索会话数据或 cookie?当我尝试存储或打印出 cookie 时,它​​告诉我数组为空。我已经尝试过 request.requestCookies 和 request.responseCookies。

NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"test_user", @"username", @"pass", @"password", nil];

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://127.0.0.1:8000/login/"]];

NSError *error;
NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];

if ( error ) {
    NSLog( @"ERROR - %@", error.localizedDescription );
} else {
    __block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request addRequestHeader: @"Content-Type" value:@"application/json; charset=utf-8"]; 
    [request appendPostData:data];
    [request setRequestMethod:@"POST"];

    [request setCompletionBlock:^{

        UIAlertView *alerView = [[UIAlertView alloc] initWithTitle:@"Login"
                                                           message:@"Login was sent"
                                                          delegate:nil
                                                 cancelButtonTitle:nil
                                                 otherButtonTitles:@"Ok", nil];
        [alerView performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:NO];

        NSLog(@"RESPONSE: %@", [[NSString alloc] initWithData:request.responseData encoding:NSUTF8StringEncoding]);//, [request.requestCookies objectAtIndex:0]);
        NSLog(@"COOKIE: %@", [request.requestCookies objectAtIndex:0]);
        [ASIHTTPRequest addSessionCookie:[request.requestCookies objectAtIndex:0]];

    }];
4

1 回答 1

0

好的,所以我解决了这个问题,结果发现在服务器端我输入了数据,但没有使用 Django 正式登录(没有返回正确的 cookie),这意味着我的应用程序没有收到正确的标头。

于 2012-04-26T17:13:55.390 回答