这是我编写的用于连接到服务器并获取用户身份验证令牌的方法:
+ (void)getAuthTokenForUsername:(NSString *)username
password:(NSString *)password
completionHandler:(void (^)(NSString *, NSError *))completionHandler
{
username = [username URLEncodedString];
password = [password URLEncodedString];
NSString *format = @"https://%@:%@@api.example.com/v1/user/api_token?format=json";
NSString *string = [NSString stringWithFormat:format, username, password];
NSURL *URL = [NSURL URLWithString:string];
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:URL]
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *URLResponse, NSData *data, NSError *error)
{
NSString *token;
if (data) {
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
token = [NSString stringWithFormat:@"%@:%@", username, dictionary[@"result"]];
}
completionHandler(token, error);
}];
}
然后一个 URL 看起来像这样:https://username:hello%C2%B0@api.example.com/v1/user/api_token?format\=json
,其中密码是hello°
。该URLEncodedString
方法正确地编码了示例中的所有内容,但请求永远不会起作用。问题不在于转义或服务器,因为我可以curl
使用相同的 URL,并且我得到了很好的 JSON 和身份验证工作,即使密码中有一个非 ASCII 字符。它也适用于其他编程语言,如ruby
or python
。但是相同的 url 永远无法使用,NSURLConnection
而且它在 Safari 中也无法使用,当然它使用NSURLConnection
. 我每次都收到“无法完成操作”和“401 禁止”。
(当密码只包含 ASCII 字符时,我的代码可以正常工作。我也尝试使用这些NSURLCredential
方法,同样的问题。)
我需要做什么才能使用密码包含非 ASCII 字符NSURLConnection
的 URL ?https://username:hello%C2%B0@api.example.com/v1/user/api_token?format\=json