【问题标题】:NSMutableURLRequest loses session informationNSMutableURLRequest 丢失会话信息
【发布时间】:2011-07-21 15:36:35
【问题描述】:

我有一个 iPhone 应用程序,我正试图与 Rails 后端对话。我正在使用 NSMutableURLRequest 来回拉取数据。所有调用在 GET 请求上都可以正常工作,但是当我需要发布数据时,我的 rails 应用程序似乎无法找到会话。我已经为 get 和 POST 请求发布了下面的代码。

这是 POST 请求:

//Set up the URL
NSString *url_string = [NSString stringWithFormat:@"https://testserver.example.com/players.xml"];
NSURL *url = [NSURL URLWithString:url_string];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                         cachePolicy:NSURLRequestReloadIgnoringCacheData 
                                     timeoutInterval:30];

//To create an object in rails
//We have to use a post request
////This is the format when using xml
NSString *requestString = [[NSString alloc] initWithFormat:@"<player><team_game_id>%@</team_game_id><person_id>%@</person_id></player>", game, person];


NSData *requestData = [NSData dataWithBytes:[requestString UTF8String] length:[requestString length]];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:requestData];
NSString *postLength = [NSString stringWithFormat:@"%d", [requestData length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];

//For some reason rails will not take application/xml
[request setValue:@"application/xml" forHTTPHeaderField:@"content-type"];

获取请求是:

NSString *url_string = [NSString stringWithFormat:@"https://testserver.example.com/people/find_by_passport?passport=%i", passport];
passportString = [[NSMutableString alloc] initWithFormat:@"%i", passport];
NSLog(@"The passport string is %@", passportString);

NSLog(url_string, nil);
NSURL *url = [NSURL URLWithString:url_string];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                         cachePolicy:NSURLRequestReloadIgnoringCacheData 
                                     timeoutInterval:30];

我在这里竭尽全力试图找出发生了什么,所以任何帮助都将不胜感激。

【问题讨论】:

    标签: iphone ios session nsurlrequest nsmutableurlrequest


    【解决方案1】:

    面临同样的问题。解析 Set-Cookie 标头的响应标头,手动提取 cookie,在后续请求中将它们作为 Cookie: 标头传回。

    如果这只是最简单的会话,您不必担心持久性、HTTPS、域/路径等。

    编辑:我找到了 NSHTTPCookieStorage 类。看看能不能帮上忙……

    【讨论】:

    • 所以我有点明白我在这里想要做什么,但我觉得我错过了一些东西,我将 Set-Cookie 拉成一个字符串,将它存储在一个钥匙串项目中,在下一个请求中将其重新拾取并将其添加到 http 标头字段中。这就是我需要做的,你说的“手动提取饼干”是什么意思?
    • 实际上我发现了同样的事情,我尝试将 cookie 添加回该标题,但它似乎对我没有任何帮助..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多