如何使用NSURLRequest设置Cookie?

时间:2022-08-23 10:11:27

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

我正在尝试在我的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];

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,以便网站知道我已登录。

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?

我搜索了互联网,但没有找到任何有用的东西。那么当我登录时,如何创建cookie?当我要去“已保存”区域中的另一个链接时,我是否每次都要发布此cookie?

Hope you unterstand my problem.

希望你解开我的问题。

Greetz

格尔茨

4 个解决方案

#1


28  

Try this

尝试这个

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

Edit:

编辑:

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

OP想知道如何创建cookie。所以这里有一些代码

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];

#2


4  

not sure it's still relevant, but in case someone find that useful, here's how you get the cookies after making a request. You should implement the selector connectionDidFinishLoading: in the object that was specified as a delegate to NSURLConnection (self in your case):

不确定它是否仍然相关,但万一有人发现有用,这里是你如何在提出请求后获得cookie。您应该在指定为NSURLConnection的委托的对象中实现选择器connectionDidFinishLoading :(在您的情况下为self):

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

in this connectionDidFinishLoading: selector you can access the cookies like that:

在这个连接DidFinishLoading:选择器,您可以访问这样的cookie:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSHTTPCookieStorage * storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    NSArray * cookies = [storage cookiesForURL:connection.currentRequest.URL];
    for (NSHTTPCookie * cookie in cookies)
    {
        NSLog(@"%@=%@", cookie.name, cookie.value);
        // Here you can store the value you are interested in for example
    }
}

then later, this stored value can be used in requests like this:

然后,这个存储的值可以在这样的请求中使用:

[request setValue:[NSString stringWithFormat:@"%@=%@", cookieName, cookieValue] forHTTPHeaderField:@"Cookie"];

or more advanced setAllHTTPHeaderFields:, but remember to use the correct value in NSHTTPCookiePath field, see details here

或更高级的setAllHTTPHeaderFields:,但请记住在NSHTTPCookiePath字段中使用正确的值,请在此处查看详细信息

also NSHTTPCookieStorage has selector -setCookies:forURL:mainDocumentURL: that can also be used to set cookies.

NSHTTPCookieStorage也有选择器-setCookies:forURL:mainDocumentURL:它也可用于设置cookie。

#3


2  

I had the same problem with a WKWebView showing the cookie on a PHP page on initial load but the cookie was cleared when page was reloaded/refreshed. Here's what I did to make it work.

我遇到了同样的问题,WKWebView在初始加载时显示PHP页面上的cookie,但是当重新加载/刷新页面时cookie被清除。这就是我做的工作。

My WKWebView with the cookie setting:

我的WKWebView与cookie设置:

WKWebViewConfiguration *webViewConfig = [[WKWebViewConfiguration alloc] init]; // empty for now
_awesomeWebView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:webViewConfig];
_awesomeWebView.UIDelegate = self;
[self.view addSubview:_awesomeWebView];

NSString *url = @"https://phpwebsitewithcookiehandling.com";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];

// set all the cookies from my NSHTTPCookieStorage in the WKWebView too
[request setHTTPShouldHandleCookies:YES];
[request setAllHTTPHeaderFields:[NSHTTPCookie requestHeaderFieldsWithCookies:[NSHTTPCookieStorage sharedHTTPCookieStorage].cookies]];

// set the cookie on the initial load
NSString *cookie = @"status=awesome";
[request setValue:cookie forHTTPHeaderField:@"Cookie"];
NSLog(@"cookie set in WKwebView header: %@", cookie);

[_awesomeWebView loadRequest:request];

On my phpwebsitewithcookiehandling.com I used the following to verify it worked:

在我的phpwebsitewithcookiehandling.com上,我使用以下内容验证它是否有效:

<?php
    echo "<li>status is: " . $_COOKIE['status'];

    // Here comes the magic which set the servers SET-COOKIE header (apparently) so it works on consecutive page loads
    setcookie('status', $_COOKIE['status'], time() + (86400 * 30), '/');

    echo '<li><a href="">Blank reload</a>';
    echo '<li><a href="#" onclick="location.reload(true);">Javascript reload</a>';

    exit;
?>

It worked for me after much trial and error. Good luck. :)

经过多次试验和错误,它对我有用。祝你好运。 :)

#4


0  

There is source code to extract cookie string from NSHTTPURLResponse:

有源代码从NSHTTPURLResponse中提取cookie字符串:

static NSString *CookieFromResponse(NSHTTPURLResponse *response) {
    NSArray<NSHTTPCookie *> *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:response.allHeaderFields forURL:response.URL];

    NSMutableString *cookieStr = [NSMutableString string];
    for (NSHTTPCookie *cookie in cookies) {
        if (cookieStr.length) {
            [cookieStr appendString:@"; "];
        }
        [cookieStr appendFormat:@"%@=%@", cookie.name, cookie.value];
    }
    return cookieStr.length ? cookieStr : nil;
}

And to set cookie string to NSMutableURLRequest:

并将cookie字符串设置为NSMutableURLRequest:

NSString *cookieStr = CookieFromResponse(response);
[request addValue:cookieStr forHTTPHeaderField:@"Cookie"];

#1


28  

Try this

尝试这个

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

Edit:

编辑:

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

OP想知道如何创建cookie。所以这里有一些代码

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];

#2


4  

not sure it's still relevant, but in case someone find that useful, here's how you get the cookies after making a request. You should implement the selector connectionDidFinishLoading: in the object that was specified as a delegate to NSURLConnection (self in your case):

不确定它是否仍然相关,但万一有人发现有用,这里是你如何在提出请求后获得cookie。您应该在指定为NSURLConnection的委托的对象中实现选择器connectionDidFinishLoading :(在您的情况下为self):

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

in this connectionDidFinishLoading: selector you can access the cookies like that:

在这个连接DidFinishLoading:选择器,您可以访问这样的cookie:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSHTTPCookieStorage * storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    NSArray * cookies = [storage cookiesForURL:connection.currentRequest.URL];
    for (NSHTTPCookie * cookie in cookies)
    {
        NSLog(@"%@=%@", cookie.name, cookie.value);
        // Here you can store the value you are interested in for example
    }
}

then later, this stored value can be used in requests like this:

然后,这个存储的值可以在这样的请求中使用:

[request setValue:[NSString stringWithFormat:@"%@=%@", cookieName, cookieValue] forHTTPHeaderField:@"Cookie"];

or more advanced setAllHTTPHeaderFields:, but remember to use the correct value in NSHTTPCookiePath field, see details here

或更高级的setAllHTTPHeaderFields:,但请记住在NSHTTPCookiePath字段中使用正确的值,请在此处查看详细信息

also NSHTTPCookieStorage has selector -setCookies:forURL:mainDocumentURL: that can also be used to set cookies.

NSHTTPCookieStorage也有选择器-setCookies:forURL:mainDocumentURL:它也可用于设置cookie。

#3


2  

I had the same problem with a WKWebView showing the cookie on a PHP page on initial load but the cookie was cleared when page was reloaded/refreshed. Here's what I did to make it work.

我遇到了同样的问题,WKWebView在初始加载时显示PHP页面上的cookie,但是当重新加载/刷新页面时cookie被清除。这就是我做的工作。

My WKWebView with the cookie setting:

我的WKWebView与cookie设置:

WKWebViewConfiguration *webViewConfig = [[WKWebViewConfiguration alloc] init]; // empty for now
_awesomeWebView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:webViewConfig];
_awesomeWebView.UIDelegate = self;
[self.view addSubview:_awesomeWebView];

NSString *url = @"https://phpwebsitewithcookiehandling.com";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];

// set all the cookies from my NSHTTPCookieStorage in the WKWebView too
[request setHTTPShouldHandleCookies:YES];
[request setAllHTTPHeaderFields:[NSHTTPCookie requestHeaderFieldsWithCookies:[NSHTTPCookieStorage sharedHTTPCookieStorage].cookies]];

// set the cookie on the initial load
NSString *cookie = @"status=awesome";
[request setValue:cookie forHTTPHeaderField:@"Cookie"];
NSLog(@"cookie set in WKwebView header: %@", cookie);

[_awesomeWebView loadRequest:request];

On my phpwebsitewithcookiehandling.com I used the following to verify it worked:

在我的phpwebsitewithcookiehandling.com上,我使用以下内容验证它是否有效:

<?php
    echo "<li>status is: " . $_COOKIE['status'];

    // Here comes the magic which set the servers SET-COOKIE header (apparently) so it works on consecutive page loads
    setcookie('status', $_COOKIE['status'], time() + (86400 * 30), '/');

    echo '<li><a href="">Blank reload</a>';
    echo '<li><a href="#" onclick="location.reload(true);">Javascript reload</a>';

    exit;
?>

It worked for me after much trial and error. Good luck. :)

经过多次试验和错误,它对我有用。祝你好运。 :)

#4


0  

There is source code to extract cookie string from NSHTTPURLResponse:

有源代码从NSHTTPURLResponse中提取cookie字符串:

static NSString *CookieFromResponse(NSHTTPURLResponse *response) {
    NSArray<NSHTTPCookie *> *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:response.allHeaderFields forURL:response.URL];

    NSMutableString *cookieStr = [NSMutableString string];
    for (NSHTTPCookie *cookie in cookies) {
        if (cookieStr.length) {
            [cookieStr appendString:@"; "];
        }
        [cookieStr appendFormat:@"%@=%@", cookie.name, cookie.value];
    }
    return cookieStr.length ? cookieStr : nil;
}

And to set cookie string to NSMutableURLRequest:

并将cookie字符串设置为NSMutableURLRequest:

NSString *cookieStr = CookieFromResponse(response);
[request addValue:cookieStr forHTTPHeaderField:@"Cookie"];