base 64编码用于具有多种语言的基本授权标头

时间:2014-05-05 15:49:17

标签: objective-c base64 basic-authentication multilingual

我正在尝试从ios应用程序登录到Jira实例,我遇到了基本64位编码授权标题的一些问题,其中用户名的字符为“ñ”,“ó”等。

我从字符串中获取数据时使用 NSISOLatin1StringEncoding 解决了这个问题。但这不适用于其他用户,例如俄罗斯用户等。

那么,我怎样才能从用户获得正确的base 64编码字符串:密码,无论用户名是什么语言?

这是我正在使用的代码

-(NSString *) baseEncode{

NSString *username = @"привет";
NSString *password = @"123привет";

NSString *basic = [NSString stringWithFormat:@"%@:%@", username, password];
NSString *string = @"";

//this way works, but not with russian users
NSData *data = [basic dataUsingEncoding:NSISOLatin1StringEncoding];

//if i use this line instead it won't work with latin users with 'ñ', 'ó', etc on their username
//NSData *data = [basic dataUsingEncoding:NSUTF8StringEncoding];


if (data != nil) {
    if ([data respondsToSelector:@selector(base64EncodedStringWithOptions:)]) {
        string = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];  // iOS 7+
    } else {
        if ([data respondsToSelector:@selector(base64Encoding)]) {
            string = [data performSelector:@selector(base64Encoding)];  // pre iOS7
        }
    }
}

NSLog(@"encode result : %@", string);
return string;

}

-(void) doRequest{

NSURL *url = [NSURL URLWithString:[@"http://url_to_jira_rest_api" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

NSString *login = [self baseEncode];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

[request setValue:@"application/json; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];

[request setValue:[NSString stringWithFormat:@"Basic %@", login] forHTTPHeaderField:@"Authorization"];

[request setHTTPMethod:@"GET"];

NSOperationQueue *queue = [[NSOperationQueue alloc] init];

[queue setSuspended:NO];

[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData * data, NSError *error) {
    NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
    long statusCode = 0;

    statusCode = [httpResponse statusCode];

    NSString* newStr = [[NSString alloc] initWithData:data
                                             encoding:NSUTF8StringEncoding];

    NSLog(@"%@",newStr);

    NSLog(@"%@",[error description]);

}];
}

这是服务器响应

Error Domain=NSURLErrorDomain Code=-1012 "The operation couldn’t be completed. (NSURLErrorDomain error -1012.)"

0 个答案:

没有答案