目的:利用NSURLSession获取token.(NSURLConnection被弃用)
融云获取token:
//实例化
NSURLSession *session = [NSURLSession sharedSession];
//定义NSMutableURLRequest
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://api.cn.ronghub.com/user/getToken.json"]];
request.HTTPMethod = @"POST";
NSString *nonce = [NSString stringWithFormat:@"%d", arc4random()];
NSString *date = [NSString stringWithFormat:@"%f",[[[NSDate alloc] init] timeIntervalSince1970]];
NSString *timestamp = [self sha1:[NSString stringWithFormat:@"%@%@%@", @"bSFbDeDXB9tBvC", nonce, date]];
[request setValue:@"pgyu6atqylj5u" forHTTPHeaderField:@"App-Key"];
[request setValue:nonce forHTTPHeaderField:@"Nonce"];
[request setValue:date forHTTPHeaderField:@"Timestamp"];
[request setValue:timestamp forHTTPHeaderField:@"Signature"];
NSString *body = [NSString stringWithFormat:@"userId=%@&name=%@&portraitUri=%@",@"panda",@"wx",@"http%3A%2F%2Fabc.com%2Fmyportrait.jpg"];
request.HTTPBody = [body dataUsingEncoding:NSUTF8StringEncoding];
//实例NSURLSessionTask
NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) {
NSLog(@"error %@", error);
} else {
NSString *stringH = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"response %@ \n%@", response, stringH);
}
}];
//请求开始
[task resume];
sha1:
//别忘了导入加密库
#import <CommonCrypto/CommonDigest.h>
- (NSString*)sha1:(NSString *)hashString
{
const char *cstr = [hashString cStringUsingEncoding:NSUTF8StringEncoding];
NSData *data = [NSData dataWithBytes:cstr length:hashString.length];
uint8_t digest[CC_SHA1_DIGEST_LENGTH];
CC_SHA1(data.bytes, (CC_LONG)data.length, digest);
NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
[output appendFormat:@"%02x", digest[i]];
return output;
}