1

我有 drupal webservice 通过目标 c 发布(保存)项目。我用谷歌搜索,发现我需要为此设置 cookie。所以我做了以下事情:

NSURL *url = [[NSURL alloc] initWithString:@"http://lanetteam.net/kaleio/services/session/token"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSURLResponse *response = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSString* csrf;
csrf = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
NSString *str = [NSString stringWithFormat:@"http://lanetteam.net/kaleio/node?title=%@&body[und][0][value]=%@",_txtTitle.text,txtContent.text];

NSURL *url1 = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request1= [[NSMutableURLRequest alloc] initWithURL:url1];
NSURLResponse *response1 = nil;
[request1 setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
[request1 addValue:csrf forHTTPHeaderField:@"X-CSRFToken"];

NSDictionary *properties = [NSDictionary dictionaryWithObjectsAndKeys:
                            @"Cookie", NSHTTPCookieName,
                            [NSString stringWithFormat:@"%@=%@", [appDelegate.dictUserProfile valueForKey:@"session_name"],[appDelegate.dictUserProfile valueForKey:@"sessionid"]], NSHTTPCookieValue,
                            nil];
NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:properties]; //**error here, cookie is returned as nil**

NSArray* cookies = [NSArray arrayWithObjects: cookie, nil];



NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];


[request1 setAllHTTPHeaderFields:headers];

NSData *responseData1 = [NSURLConnection sendSynchronousRequest:request1 returningResponse:&response1 error:nil];

NSMutableArray *jsonArray=[NSJSONSerialization JSONObjectWithData:responseData1 options:NSJSONReadingMutableContainers error:nil];

NSLog(@"data : %@", jsonArray);

我在上面提到了错误发生的位置。请让我知道我该如何解决这个问题,自从过去很多天以来我一直在尝试这个。如果不设置 cookie,我会收到以下错误:

CSRF validation failed
4

2 回答 2

2

我也遇到同样的问题。设置令牌后,我收到错误 CSRF 验证失败。但我得到了解决方案,我认为在调用任何 Web 服务之前它不合适。呼叫注销服务它对我有用

于 2015-02-26T10:25:32.237 回答
0

您需要获取 X-CSRF-Token 并将其放入您的标题中。

登录后,您可以通过以下方式从浏览器获取令牌:http: //yoursite.com/services/session/token

然后,将令牌放在所有请求的标头中:

X-CSRF-Token=<token>

另请参阅: 如何在 iOS 中获取 CSRF 令牌?

于 2013-10-13T02:43:06.557 回答