在IOS中使用带有网关保护的JSON Webservice时没有响应



下面的代码是简单的登录应用程序。我使用Post请求通过用户名和密码来获取详细信息。但我得到@"响应从web服务。

email= emailTextField.text;
password=passwordTextfield.text;
NSString *post = [[NSString alloc] initWithFormat:@"UserName=%@&Password=%@",email,password];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSURL *url = [NSURL URLWithString:@"http:Gateway/api/json"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:@"POST"];
[theRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[theRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];
[theRequest setHTTPBody:postData];
[theRequest setHTTPBody:postData];
NSURLResponse *response;// = [[NSURLResponse alloc] init];
NSError *error;// = [[NSError alloc] init;
NSData *urlData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(@"Login response: is %@",str);

使用NSURLConnection委托为服务器提供身份验证凭据

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    if ([challenge previousFailureCount] == 0) {
        NSURLCredential *credential;
        credential = [NSURLCredential credentialWithUser:userName password:password persistence:NSURLCredentialPersistenceNone];
        [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
    } else {
        [[challenge sender] cancelAuthenticationChallenge:challenge];
    }
}

最新更新