2

之前的问题是关于我每次都必须登录才能进行网络服务(例如发布链接或上传图片)的问题。Philipe 回答说我必须为每个请求使用 cookie 而不是登录过程。我发现了这种获取cookie的方法:

- (void)getCookies {

    NSHTTPURLResponse * response;
    NSError * error;
    NSMutableURLRequest *request;

    request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://MyWebsite.com/login.php"]
                                            cachePolicy:NSURLRequestReloadIgnoringCacheData
                                        timeoutInterval:120];
    NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

    NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]);
    NSArray * all = [NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:[NSURL URLWithString:@"http://MyWebsite.com/login.php"]];
    NSLog(@"%d", all.count);

    for (NSHTTPCookie *cookie in all) {
        NSLog(@"Name: %@ : Value: %@", cookie.name, cookie.value);
        NSLog(@"Comment: %@ : CommentURL: %@", cookie.comment, cookie.commentURL);
        NSLog(@"Domain: %@ : ExpiresDate: %@", cookie.domain, cookie.expiresDate);
        NSLog(@"isHTTPOnly: %c : isSecure: %c", cookie.isHTTPOnly, cookie.isSecure);
        NSLog(@"isSessionOnly: %c : path: %@", cookie.isSessionOnly, cookie.path);
        NSLog(@"portList: %@ : properties: %@", cookie.portList, cookie.properties);
        NSLog(@"version: %u", cookie.version);
    }
} 

我还发现这段代码可以使用这些 cookie,但我不知道如何使用它:

[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookies];

这是我的 POST 方法,我使用的是 RestKit API:

- (IBAction)addLinkPressed:(UIButton *)sender {

        [RKClient clientWithBaseURLString:@"http://MyWebsite.com"];

        NSDictionary* params = [NSDictionary dictionaryWithObjectsAndKeys:
                                self.linkField.text, @"url",
                                self.linkTitleField.text, @"title",
                                self.linkSummaryField.text, @"summary",
                                nil];

        RKRequest *request = [[RKClient sharedClient] post:@"/send_link.php" params:params delegate:self];
        [request setUserData:@"sendLink"];   
}

问题:我应该存储 cookie 的哪个属性以将其用于登录信息,我应该将它放在我的代码中的什么位置?

4

1 回答 1

0
[request setHTTPMethod:@"POST"];
于 2013-10-23T05:31:55.610 回答