如何在目标c中为Get方法添加Header中的Authorization

时间:2017-07-26 04:39:23

标签: ios objective-c

我想在授权标题

中添加我的令牌
NSURL *url2 = @"http://54.149.31.77:3000/api/search?number=98745612661";

        NSLog(@"%@  urlis ====>",urlString);

        NSData *data = [NSData dataWithContentsOfURL:url2];
        NSString *ret = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSData *dataaa = [ret dataUsingEncoding:NSUTF8StringEncoding];
        id json = [NSJSONSerialization JSONObjectWithData:dataaa options:0 error:nil];
        NSArray * resultDict =[json objectForKey:@"name"];

3 个答案:

答案 0 :(得分:0)

您可以使用NSMutableRequest -

  NSURL *url2 = @"http://54.149.31.77:3000/api/search?number=98745612661";
  NSURLSession *session = [NSURLSession sharedSession];

  NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url2];

  [request setHTTPMethod:@"GET"];

  [request setValue:[[NSUserDefaults standardUserDefaults] valueForKey:@"token"] forHTTPHeaderField:@"Authorization"];
  [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

   // add any additional headers or parameters
   NSURLSessionDataTask *downloadTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if (!error) {
   // do your response handling
   id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSArray * resultDict =[json objectForKey:@"name"];
  }
  }];

  [downloadTask resume];

要更详细地了解NSURLSession,请参阅此Tutorial

答案 1 :(得分:0)

你可以通过

传递它
[request setValue:@"Your Token" forHTTPHeaderField:@"Authorization"];

已编辑:

根据您的评论,如果您想更改回复,则应使用NSMutableDictionary代替NSArray

注意:您的响应应该是Dictionary,如果它将是数组,则使用NSMutableArray

NSMutableDictionary * resultDict =[json objectForKey:@"name"];
[resultDict setObject:@"Your Token" forKey:@"Authorization"];

答案 2 :(得分:0)

NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];

[request addValue:VALUE forHTTPHeaderField:@"Authorization"];

尝试创建Mutable请求并向其添加授权标头。您可以将此请求作为参数发送给任何人。 AFNetworking(或某些第三方网络)库API调用或URLSession(Apple)

有关NSMutableRequest

的更多信息