NSURLSession的簡單使用

目的:利用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;
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • 簡介 我們都知道在iOS9.0之后,以前使用的NSURLConnection已經過期,蘋果推薦我們使用NSURLS...
    Mark_Guan閱讀 923評論 0 4
  • 218.241.181.202 wxhl60 123456 192.168.10.253 wxhl66 wxhl6...
    CYC666閱讀 1,553評論 0 6
  • 寫在前面融云是一個比較強大的第三方框架,為我們提供了即時通訊的基本組件,導入SDK,進行一些簡單的配置就可以看到會...
    汪小喵閱讀 14,827評論 14 31
  • Spring Cloud為開發(fā)人員提供了快速構建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,569評論 19 139
  • 文/盧拉 對于一座城市,我們留戀的是什么?是食物?是故事?還是故事里的人?走過了那么多城市,每一座城市都有特色美食...
    盧拉閱讀 1,064評論 30 16

友情鏈接更多精彩內容