NSString *Str = @"Basic YnRwaXhlbDoxMjM0NQ==";
NSArray *keys = [NSArray arrayWithObjects: @"Authorization",nil];
NSArray *objects = [NSArray arrayWithObjects:Str,nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSError * error = nil;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:NSJSONReadingMutableContainers error:&error];
NSURL *urlStr1 = [NSURL URLWithString:@"http://192.168.0.49/bubbletop/index.php?route=feed/rest_api/gettoken&grant_type=client_credentials"];
NSMutableURLRequest *request1 = [[NSMutableURLRequest alloc] initWithURL:urlStr1];
[request1 setHTTPMethod:@"POST"];
[request1 setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request1 setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request1 setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[jsonData length]] forHTTPHeaderField:@"Content-Length"];
[request1 setHTTPBody: jsonData];
_connection = [[NSURLConnection alloc]initWithRequest:request1 delegate:self startImmediately:YES];
NSData *data1 = [NSData dataWithContentsOfURL:urlStr1];
NSDictionary *fashionJson = [NSJSONSerialization JSONObjectWithData:data1 options:kNilOptions error:nil];
NSLog(@"requestReply: %@", fashionJson);
此处我将标题字段参数作为Basic YnRwaXhlbDoxMjM0NQ==
传递给密钥Authorization
,但将数据设为nil并将日志记录为
requestReply :( null)
答案 0 :(得分:0)
我认为你将标题字段添加为错误的
不喜欢
NSString *Str = @"Basic YnRwaXhlbDoxMjM0NQ==";
NSArray *keys = [NSArray arrayWithObjects: @"Authorization",nil];
NSArray *objects = [NSArray arrayWithObjects:Str,nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSError * error = nil;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:NSJSONReadingMutableContainers error:&error];
像HTTP令牌身份验证一样
[request1 addValue:@"Basic YnRwaXhlbDoxMjM0NQ==" forHTTPHeaderField:@"Authorization"];
注意强>
不需要在这里附加身体
[request1 setHTTPBody: jsonData];
请参阅示例请求,请参阅this
答案 1 :(得分:0)
由于您使用的是NSData *data1 = [NSData dataWithContentsOfURL:urlStr1];
方法,因此不会从您创建的网址请求中获取您的httpbody。实现NSURLConnection
委托方法或使用NSURLSession
加载数据。由于不推荐NSURLConnection
API,我建议使用NSURLSession
。