我在尝试从我们公司需要身份验证的网站上获取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"];
}
答案 0 :(得分:0)
您只能使用NSURLConnection
对象发出一个请求,因此您应该在发出请求之前创建它。