如何使用NSURLRequest设置Cookie? [英] How to set a Cookie with a NSURLRequest?

查看:434
本文介绍了如何使用NSURLRequest设置Cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的iPhone应用程序中创建一个登录名.

I'm trying to create an login in my iPhone App.

NSURL *urlNew = [NSURL URLWithString:urlstring];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:urlNew];
NSString *msgLength = [NSString stringWithFormat:@"%d", [parameterString length]];
[theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
[theRequest setHTTPMethod:@"POST"];
[theRequest setValue:length forHTTPHeaderField:@"Content-Length"];
[theRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[theRequest setHTTPBody: httpbody];

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];

[connection start];

这就是我将数据发布到服务器的方式,它的工作原理-我得到了答复.问题是,响应是登录端的代码,而不是保存"区域的代码.我认为我必须创建cookie,以便网站知道我已经登录.

Thats the way how I post my data to the Server, it works - i get a response. The problem is, that the response is the code of the Login-side, not the code of the "saved" area. I think I have to create cookies, so that the website knows, that I am logged in.

我搜索了互联网,但没有发现任何有用的信息.那么,当我登录时如何创建cookie?当我转到已保存"区域中的另一个链接时,是否必须每次都发布此cookie?

I searched the internet but didn't found anything useful. So how do I create a cookie, when I am loggin me in? Do I have to post this cookie everytime, when I am going to another link in the "saved" area?

希望您能理解我的问题.

Hope you unterstand my problem.

格里兹

推荐答案

尝试一下

[theRequest setValue:@"myCookie" forHTTPHeaderField:@"Cookie"];

OP想知道如何创建一个cookie.这是一些代码

OP wants to know how to create a cookie. So here is some code

NSDictionary *cookieProperties = [NSDictionary dictionaryWithObjectsAndKeys:
                        @"domain.com", NSHTTPCookieDomain,
                        @"\\", NSHTTPCookiePath,  
                        @"myCookie", NSHTTPCookieName,
                        @"1234", NSHTTPCookieValue,
                        nil];
NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
NSArray* cookieArray = [NSArray arrayWithObject:cookie];
NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookieArray];
[request setAllHTTPHeaderFields:headers];

这篇关于如何使用NSURLRequest设置Cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆