1

我在尝试从我们公司需要身份验证的站点之一获取 JSON 页面时遇到问题。

- http://xyz.com - 需要身份验证
- 我需要从http://xyz.com/jsonpage1
获取数据 - 在 View DidLoad 中,我发送用户和密码用于登录以建立会话
- 然后,我有一个按钮将请求 JSON。

此序列不起作用(意味着如果会话加载代码与 json 加载代码位于不同的例程中)。如果我在同一个例程中都有这两个代码,比如视图 didLoad,那么它似乎可以识别我的凭据并取回 JSON。奇怪的!我错过了什么?应该如何工作?我认为建立会话会创建一次 cookie 而无需再次打扰它?当我单击按钮时,我是否以某种方式丢失了 cookie?

-(void)viewDidLoad
{
  [self establishSession];
}

-(void)establishSession{   
//
//Login Session
//
NSURL *url = [NSURL URLWithString:@"http://xyz.com/login"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

NSString *post = [NSString stringWithFormat:@"username=%@&password=%@",@"abc",@"123"];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

[request setValue:[NSString stringWithFormat:@"%d",[postData length]] forHTTPHeaderField:@"Content-Length"];
[request setTimeoutInterval:15];
[request setHTTPBody:postData];
[request setHTTPMethod:@"POST"];

urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[urlConnection start];

}

- (IBAction)getJSON:(id)sender
{
 NSError *error = nil;

resultsView.text =@"";

[self establishLoginSession];   //I have to have this line here to get it to work ?????

//get JSON

NSURL *jurl = [NSURL URLWithString:@"http://xyz.com/jsonPage1"];

NSData *jdata = [NSData dataWithContentsOfURL:jurl options:NSDataReadingUncached error:&error];
NSDictionary* jsonDict = [NSJSONSerialization
                      JSONObjectWithData:jdata //1
                      options:kNilOptions
                      error:&error];

NSString *dataString = [[NSString alloc]initWithData:jdata encoding:NSUTF8StringEncoding];
resultsView.text = dataString;
} 


//Not sure if I need the cookie??
-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse  *)response
{

NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse*) response;
NSDictionary *fields = [HTTPResponse allHeaderFields];

if([fields valueForKey:@"Set-Cookie"])
   cookie = [fields valueForKey:@"Set-Cookie"];

}
4

1 回答 1

0

您只能对一个NSURLConnection对象发出一个请求,因此您应该在发出请求之前立即创建它。

于 2012-08-19T05:35:54.833 回答