0

我正在尝试使用以下代码登录网站并使用 JSON 获得响应:

@try {

    if([[txtUsername text] isEqualToString:@""] || [[txtPassword text] isEqualToString:@""] ) {
        [self alertStatus:@"Please enter both Username and Password" :@"Login Failed!"];
    } else {
        NSString *post =[[NSString alloc] initWithFormat:@"username=%@&password=%@",[txtUsername text],[txtPassword text]];
        NSLog(@"PostData: %@",post);

        NSURL *url=[NSURL URLWithString:@"https://yedion.afeka.ac.il/yedion/fireflyweb.aspx?prgname=login"];

        NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

        NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        [request setURL:url];
        [request setHTTPMethod:@"POST"];
        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPBody:postData];

        [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];

        NSError *error = [[NSError alloc] init];
        NSHTTPURLResponse *response = nil;
        NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

        NSLog(@"Response code: %d", [response statusCode]);
        if ([response statusCode] >=200 && [response statusCode] <300)
        {
            NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
            NSLog(@"Response ==> %@", responseData);

            SBJsonParser *jsonParser = [SBJsonParser new];
            NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
            NSLog(@"%@",jsonData);
            NSInteger success = [(NSNumber *) [jsonData objectForKey:@"success"] integerValue];
            NSLog(@"%d",success);
            if(success == 1)
            {
                NSLog(@"Login SUCCESS");
                [self alertStatus:@"Logged in Successfully." :@"Login Success!"];

            } else {

                NSString *error_msg = (NSString *) [jsonData objectForKey:@"error_message"];
                [self alertStatus:error_msg :@"Login Failed!"];
            }

        } else {
            if (error) NSLog(@"Error: %@", error);
            [self alertStatus:@"Connection Failed" :@"Login Failed!"];
        }
    }
}
@catch (NSException * e) {
    NSLog(@"Exception: %@", e);
    [self alertStatus:@"Login Failed." :@"Login Failed!"];
}

在日志中我可以看到没有 JSON 响应,所以我不知道登录是否成功。有没有其他方法可以登录到这个网站并得到响应,不管它是否成功?

谢谢!

4

2 回答 2

0

该代码对我来说似乎没问题,但请检查 Web 服务并检查是否为 json 提供了正确的关键字,如果给 objectForKey 的键和您在 Web 服务中的键不同,您将永远不会得到 json 响应。

于 2013-04-03T04:23:55.003 回答
0

使用 Get 方法并尝试

[ request setHTTPMethod:@"GET" ];
于 2014-03-20T14:09:52.597 回答