Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a Cookie with a NSURLRequest?

I'm trying to create a 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];

That's 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.

I searched on the Internet but I didn't find anything useful. So how do I create a cookie, when I am logging in? Do I have to post this cookie every time, when I am going to another link in the "saved" area?

like image 654
Schmarsi Avatar asked Feb 12 '12 15:02

Schmarsi


4 Answers

Try this

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

Edit:

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];
like image 139
mbh Avatar answered Nov 05 '22 16:11

mbh


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):

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

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

- (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

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

like image 37
Anton Kryvenko Avatar answered Nov 05 '22 15:11

Anton Kryvenko


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.

My WKWebView with the cookie setting:

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:

<?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. :)

like image 3
holm50 Avatar answered Nov 05 '22 15:11

holm50


There is source code to extract cookie string from NSHTTPURLResponse:

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:

NSString *cookieStr = CookieFromResponse(response);
[request addValue:cookieStr forHTTPHeaderField:@"Cookie"];
like image 1
k06a Avatar answered Nov 05 '22 15:11

k06a