从零开始iOS:block

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

2016-06-28  本文已影响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信息}

上一篇下一篇

猜你喜欢

热点阅读