执行HTTP POST请求,然后执行HTTP GET请求

时间:2014-01-06 23:13:47

标签: ios post get nsurlsession

我是处理iOS连接的初学者。我想对网址执行POST请求和GET请求。问题是我需要先做POST,这样我就可以获得一个JSON解析的访问令牌,以后会放在GET请求的头部,这样我就可以检索出我需要的登录数据了。我正在使用自定义委托方法,但是当我运行它时,GET请求比POST早执行,所以在GET完成之前我无法获取密钥。有没有办法先执行POST然后再执行GET?这是我的代码:

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.

//params
self.user = @"carlos";
self.pass = @"1234";
self.grantType = @"password";
self.clientId = @"7da713e69afc96cf894e";
self.clientSecret = @"2c14ec54cfdfd6faec4ef56ca7f0870ab83f820b";

// Set the side bar button action. When it's tapped, it'll show up the sidebar.
self.sideBarButton.target = self.revealViewController;

self.sideBarButton.action = @selector(revealToggle:);

// Set the gesture
[self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];

[self httpPostWithCustomDelegate];

[self sendHTTPGet];

}


-(void) httpPostWithCustomDelegate
{
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];

NSURL * url = [NSURL URLWithString:@"http://192.237.241.175:8090/oauth2/access_token/"];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];
NSString * params =[NSString stringWithFormat:@"&username=%@&password=%@&grant_type=%@&client_id=%@&client_secret=%@&scope=write",self.user,self.pass,self.grantType,self.clientId,self.clientSecret];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest
                                                   completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                       NSLog(@"Retrieving Data");
                                                       // NSLog(@"Response:%@ %@\n", response, error);
                                                       if(error == nil)
                                                       {
                                                           //Test Display
                                                           //                                                               NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
                                                           //                                                               NSLog(@"Data = %@",text);

                                                           self.responseDataPost = [[NSMutableData alloc] init];
                                                           [self.responseDataPost appendData:data];

                                                           NSError *error;

                                                           NSMutableDictionary *receivedData = [NSJSONSerialization JSONObjectWithData:self.responseDataPost options:NSJSONReadingMutableContainers error:&error];

                                                           //obtener del dictionary el access token y meter como header Authorization Bearer + id

                                                           //NSArray *accessToken = [receivedData valueForKeyPath:@"access_token"];

                                                           self.connTxtPost.text = [receivedData valueForKeyPath:@"access_token"];
                                                           self.recData = [receivedData valueForKeyPath:@"access_token"];

                                                       }

                                                   }];
[dataTask resume];

}

-(void) sendHTTPGet
{
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: self delegateQueue: [NSOperationQueue mainQueue]];

NSURL * url = [NSURL URLWithString:@"http://192.237.241.175:8090/snippets/"];

NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];

[urlRequest setHTTPMethod:@"GET"];
self.connTxtGet.text = self.recData ;

[urlRequest setValue:self.recData forHTTPHeaderField:@"Authorization"];


NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest
                                                   completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                       //NSLog(@"Response:%@ %@\n", response, error);
                                                       if(error == nil)
                                                       {
                                                           NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
                                                           NSLog(@"Data = %@",text);

                                                       }

                                                   }];

[dataTask resume];

}

1 个答案:

答案 0 :(得分:0)

您无需一起调用这两种方法。

[self httpPostWithCustomDelegate];
[self sendHTTPGet];

您正在同时提出两项请求。但是哪个响应首先是你无法确定的。因为您需要来自“POST”请求的数据来发出“GET”请求。做这样的事情:

-(void) httpPostWithCustomDelegate{
  .............
  NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest
                                               completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                       ...................
                                                       ...................
                                                       self.connTxtPost.text = [receivedData valueForKeyPath:@"access_token"];
                                                       self.recData = [receivedData valueForKeyPath:@"access_token"];
                                                       [self sendHTTPGet];
                                                   }

                                               }];
    [dataTask resume];
  }

这将确保您在发出“GET”请求时拥有“access_token”。希望这会很好。 :)