如何进行身份验证的服务调用

时间:2012-05-24 13:32:47

标签: ios nsurlconnection

您好我正在尝试连接到一些将使用用户名和密码作为凭据的服务器。以下是我正在使用的代码。     NSString post = [[NSString alloc] initWithFormat:@“userName = *& password = * ”];     NSURL url = [NSURL URLWithString:@“ ** * *** ”];

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

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

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSLog(@"request:%@",request);
     urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

这里的问题是服务器正在给用户无效的消息。但我提供的凭据很好。这个用户名和密码不在请求对象中..你们中的任何人都可以帮助我..

2 个答案:

答案 0 :(得分:0)

您需要以包含用户名和字符串的字符串开头。密码。这将形成http POST主体。您需要替换username_input_field& password_input_field,其中包含Web服务器的正确输入字段名称。我的建议是使用Firefox和httpFox扩展程序登录您的网络服务器。 httpFox将显示请求的所有输入字段名称。您可能还需要添加额外的隐藏字段。

NSString *post = [NSString stringWithFormat:
    @"username_input_field=%@&password_input_field=%@",username,password]; 

答案 1 :(得分:0)

将用户名添加到请求标头对象中,如下所示:

[request addValue:@"<username>" forKey:@"<username parameter>"]