如何从iOS中的URL获取cookie?

时间:2014-05-31 07:26:42

标签: ios objective-c encoding base64

我有一个应用程序,我必须使用URL创建会话,并需要从该URL获取cookie并将cookie传递给webview,以便它不会要求任何用户名和密码。

为此,我使用此代码:

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

}

这是我的Android代码。我可以在Android中获取cookie:

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);
        }

我正在尝试从我的combinedString(用户名:密码)中获取base64encoded字符串,但问题是我的base64encodedstring返回nil。

1 个答案:

答案 0 :(得分:0)

您是否使用此代码:https://github.com/nicklockwood/Base64

如果您这样做,则应使用- (NSString *)base64EncodedString;代替 所以你的代码应该是这样的:

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

关于Cookie,您可以从-[NSURLConnection sendSynchronousRequest:returningResponse:error:]的“returnsResponse”传出参数中获取它们 您应该将NSHTTPURLResponse指针的地址传递给它 所以你的代码应该是这样的:

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

编辑:根据您的要求,要将Cookie设置为NSMutableURLRequest,您必须使用上面的NSArray *cookies。这是代码:

// 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...