0

I have an application where I have to create session using a URL and need to get cookie from that URL and pass the cookie to webview so that it won't ask for any username and password.

For that I am using this code:

- (void)getcookie {

  NSURL* aUrl =
      [NSURL URLWithString:@"https://www.sessioncheck.com/session/create"];
  NSMutableURLRequest* request =
      [NSMutableURLRequest requestWithURL:aUrl
                              cachePolicy:NSURLRequestUseProtocolCachePolicy
                          timeoutInterval:30.0];
  NSString* email = @"tina@gmail.com";
  NSString* password = @"abcde@123";


  NSString* combinedString =
      [NSString stringWithFormat:@"%@:%@", email, password];
  NSString* base64encodedstring =
      [NSString stringWithBase64EncodedString:combinedString];
  NSData* base64data = [NSData dataWithBase64EncodedString:combinedString];

  [request addValue:[NSString stringWithFormat:@"Basic %@", base64encodedstring]
      forHTTPHeaderField:@"Authorization"];
  [request setHTTPMethod:@"GET"];

  NSError* error = nil;
  NSData* returnData = [NSURLConnection sendSynchronousRequest:request
                                             returningResponse:nil
                                                         error:&error];
  if (returnData != nil) {
    NSDictionary* JSONDictionary =
        [NSJSONSerialization JSONObjectWithData:returnData
                                        options:kNilOptions
                                          error:&error];
  }

}

This is my Android code. I am able to get cookie in Android:

HttpGet get;
        try {
            get = new HttpGet(
                    new URI("https://www.sessioncheck.com/session/create"));
            byte[] encodedBytes = Base64.encodeBase64((email+":"+password).getBytes());
            //System.out.println("encodedBytes " + new String(encodedBytes));
            get.setHeader("Authorization", "Basic " + new String(encodedBytes));
            http.execute(get);

            List<Cookie> cookies = ((DefaultHttpClient)http).getCookieStore().getCookies();
            for (int i = 0; i < cookies.size(); i++) {
                cookie = cookies.get(i);
            }

            String cookieString = cookie.getName() + "=" + cookie.getValue();
            signedin.storeCookie("cookie", cookieString);
        }

I am trying to get the base64encoded string from my combinedString(username:password) but the problem is my base64encodedstring is returning nil.

halfer
  • 19,824
  • 17
  • 99
  • 186
Rani
  • 3,333
  • 13
  • 48
  • 89
  • http://stackoverflow.com/questions/12036512/how-to-get-cookie-from-webserver-and-maintain-it-in-ios-app – Debanjan May 31 '14 at 07:31

1 Answers1

0

Did you use this code: https://github.com/nicklockwood/Base64 ?

If you did then you should use - (NSString *)base64EncodedString; instead.
So your code should look like this:

NSString* base64encodedstring = [combinedString base64EncodedString];
NSData* base64data = [base64encodedstring dataUsingEncoding:NSUTF8StringEncoding];

About cookies, you can get them from "returningResponse" outgoing parameter of -[NSURLConnection sendSynchronousRequest:returningResponse:error:].
You should pass an address of a NSHTTPURLResponse pointer into it.
So your code should be like this:

NSHTTPURLResponse *res = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request
                                           returningResponse:&res
                                                       error:&error];
NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:[res allHeaderFields]
                                                          forURL:aUrl];

EDIT : As you requested, to set cookies into a NSMutableURLRequest, you have to use the NSArray *cookies from above. Here is the code:

// Use the cookies from the code above
NSDictionary *headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:newURL];
[req setAllHTTPHeaderFields:headers];

// Do your other setups here...
3329
  • 1,411
  • 13
  • 17
  • Hi,Now i am able to get the cookie thru the url and now i want to pass this cookie to another url so that it will not ask me for any username and password.I have written the code to set cookie received from another url but it is not working – Rani Jun 01 '14 at 18:22
  • This is my code :NSUserDefaults* userdefaults = [NSUserDefaults standardUserDefaults]; NSString* cookievalu = [userdefaults valueForKey:@"cookie"]; NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:redirecturl]; [request setValue:cookievalu forHTTPHeaderField:@"Cookie"]; [request setHTTPMethod:@"POST"]; [request setHTTPShouldHandleCookies:YES]; [webview loadRequest:request]; – Rani Jun 01 '14 at 18:22
  • My cookievalu which i get is :cp_rmc=b521fec51d4d023b9770f1de6e2f462748cfdd1371a8a7538fe39d1731615d5e8597871fce7b114f4fa13ae592e7f9a39524985b9bc7f1ce002c9f589c60827c2fdcc2e39c23a042f84d0dadd7d6c996 – Rani Jun 01 '14 at 18:23
  • Pleaase help me in solving this problem – Rani Jun 01 '14 at 18:25