这是我的代码:
NSString * post = [NSString stringWithFormat:@s = aaa& r = k& c = gg]; NSData * postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]; NSString * postLength = [NSString stringWithFormat:@%d,[postData length]]; NSMutableURLRequest * request = [[NSMutableURLRequest alloc] init]; [请求setURL:[NSURL URLWithString:(@http:// localhost:8000 / messages / views /)]]; [request setHTTPMethod:@POST]; [request setValue:postLength forHTTPHeaderField:@Content-Length]; [request setValue:@application / x-www-form-urlencoded charset = utf-8forHTTPHeaderField:@Content-Type]; [请求setHTTPBody:postData]; NSError *错误; NSURLResponse * response; NSData * urlData = [NSURLConnection sendSynchronousRequest:request returnedResponse:& response error:& error]; NSString * data = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding]; NSLog(data);解决方案
通常这归结为正确设置头。已经详细说明了答案。您需要的相关部分是:
xhr.setRequestHeader(X-CSRFToken,令牌)有关从Cookie获取令牌的详细信息,请参阅链接的答案,为简洁起见,我没有将其从那里复制。我真的不知道你的代码的上下文,所以这种检索方法可能不会直接应用。无论如何,您需要以某种方式获取令牌。
当您拥有令牌时,请向 NSMutableURLRequest 中添加标题。发布请求时,错误应该已经没了。
[request addValue:token forHTTPHeaderField:@X-CSRFToken];
I send a POST request from IPhone to Django and get "CSRF verification failed", which I can't perfectly understand. I tried to find a good solution over the internet, but I couldn't . is there any simple way to POST to django?
this is my code:
NSString *post =[NSString stringWithFormat:@"s=aaa&r=k&c=gg"]; NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]; NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setURL:[NSURL URLWithString:(@"localhost:8000/messages/views/")]]; [request setHTTPMethod:@"POST"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; [request setValue:@"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody:postData]; NSError *error; NSURLResponse *response; NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding]; NSLog(data);解决方案
Normally this boils down to setting the headers correctly. There is an answer that already details this. The relevant part you need is this:
xhr.setRequestHeader("X-CSRFToken", token)See the linked answer for details on getting the token from the cookies, for brevity I didn't copy it from there. I don't really know the context of your code, so this method of retrieval might not directly apply. Regardless, you need to get the token somehow.
When you have the token, add a header to the NSMutableURLRequest. Upon posting the request, the error should be gone.
[request addValue:token forHTTPHeaderField:@"X-CSRFToken"];
更多推荐
iPhone发布到Django并获得CSRF验证失败
发布评论