美文网首页从零开始iOS:block
iOS - AFN中 将token添加到请求头

iOS - AFN中 将token添加到请求头

作者: 龙之天下 | 来源:发表于2016-06-28 16:27 被阅读2206次

    问题:AFN中将token添加到请求头

    错误信息:如下:

    Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: unauthorized (401)" UserInfo={com.alamofire.serialization.response.error.response={ URL: http://132.com/appweb/phone/web/content } { status code: 401, headers {

    "Cache-Control" = "no-cache, no-store, max-age=0, must-revalidate";

    "Content-Length" = 82;

    "Content-Type" = "application/json;charset=UTF-8";

    Date = "Tue, 28 Jun 2016 08:14:50 GMT";

    Expires = 0;

    Pragma = "no-cache";

    Server = "Apache-Coyote/1.1";

    "X-Content-Type-Options" = nosniff;

    "X-Frame-Options" = DENY;

    "X-XSS-Protection" = "1; mode=block";

    } }, NSErrorFailingURLKey=http://http://132.com/appweb/phone/web/content, com.alamofire.serialization.response.error.data=<7b22636fXXXXa>, NSLocalizedDescription=Request failed: unauthorized (401)}

    用系统方式添加请求

    //1. 发送请求

    NSURL *url = [NSURL URLWithString:urlString];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    NSURLSessionDataTask *task;

    request.HTTPMethod = @"GET";

    //2.设置将token添加到请求头---setValue:forHTTPHeaderField: 此方法是系统的方法

    [request setValue:accessToken forHTTPHeaderField:@"token"];

    //3.调用AFN的封装的方法

    - (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler;

    //例子如下:

    task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {

    if (error == nil) {  success(task, responseObject);//返回数据  // 写入缓存 } else {    failure(@"请求数据失败", error);         //网络请求失败,返回error信息}

    相关文章

      网友评论

      • 小_菜_鸟:写的一坨屎!
      • SuperObject:你写的啥?问题对应吗,解决了吗,哥们
      • i赵磊:最近后台让我传udid,地址和参数都没问题,但一直出现401错误,头好大,你这个方法可以避免401吗?
      • 8290a89231af:大哥 , 能给一个详细的demo吗 ?小弟新手 , 最近在跟后台对接口, 后台在登录成功后会返回一个token给我们, 怎么将这个token写到header? cheng080010@163.com小弟邮箱0.0多谢!盼回复

      本文标题:iOS - AFN中 将token添加到请求头

      本文链接:https://www.haomeiwen.com/subject/bkutjttx.html