这是我可以使用的示例:
-(IBAction)getToken:(id)sender {
NSString *clientSecret = (__bridge NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)CLIENT_SECRETCODE,
NULL,
(CFStringRef) @"!*'();:@&=+$,/?%#[]",
kCFStringEncodingUTF8);
NSMutableString* authHeader = [NSMutableString stringWithString:@"client_id="];
[authHeader appendString:CLIENT_ID];
[authHeader appendString:@"&client_secret="];
[authHeader appendString:clientSecret];
[authHeader appendString:@"&grant_type=client_credentials&scope=http://api.microsofttranslator.com"];
NSMutableURLRequest *request =[NSMutableURLRequest
requestWithURL:[NSURL URLWithString:TOKEN_STRING]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:@"POST"];
[request addValue:@"application/x-www-form-urlencoded"
forHTTPHeaderField:@"Content-Type"];
const char *bytes = [authHeader UTF8String];
[request setHTTPBody:[NSData dataWithBytes:bytes length:strlen(bytes)]];
NSURLResponse* response;
NSError* error;
NSData* data = [NSURLConnection sendSynchronousRequest: request returningResponse: &response error: &error];
if (data != nil) {
NSString* contents = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSString *formattedContents = [contents stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}
即使它适用于 Microsoft 翻译,也应该不难将其适用于其他服务。在这里,令牌没有被解析,代码很粗糙,因为我使用的是自动引用计数,所以应该注意,在您的配置之后可能需要自动释放。