nsurlconnection 服务器需要特殊设置吗?

发布于 2024-11-05 19:45:37 字数 655 浏览 2 评论 0原文

我想知道服务器是否应该有特殊设置来使用 nsurlconnections?当我尝试创建连接和身份验证时。我没有收到任何错误或警告,但它没有连接。

任何人都可以向我澄清这一点吗?

谢谢

编辑:这是我当前使用的代码

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"loginURl"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; 
    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; 
    [webView1 scalesPageToFit]; 
    if (theConnection) { 
        receivedData = [[NSMutableData data] retain]; 
    } else { 
        NSLog(@"Connection Failed"); 
    } 
}

I wanted to know if the server should have special setting to work with nsurlconnections? When I tried creating a connection and authentication. I don't get any error or warning but it does not connected.

Could any one please clarify me on this.

Thanks

Edit: Here is the code I currently use

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"loginURl"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; 
    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; 
    [webView1 scalesPageToFit]; 
    if (theConnection) { 
        receivedData = [[NSMutableData data] retain]; 
    } else { 
        NSLog(@"Connection Failed"); 
    } 
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

拿命拼未来 2024-11-12 19:45:37

不,您的服务器不需要任何特殊配置。 NSURLConnection 仅使用简单的 HTTP 请求。

对于身份验证:您需要自己实现身份验证所需的委托方法。另请检查您是否通过 SSL 连接并为此实现所需的委托方法。

编辑:这是我的一个使用 HTTP 身份验证的应用程序的一部分。我发现您还需要在 canAuthenticateAgainstProtectionSpace: 方法中为 NSURLAuthenticationMethodHTTPBasic 返回 YES,否则它将无法工作。

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust] || [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodHTTPBasic];
}

No, your server does not need any special config. A NSURLConnection uses just simple HTTP-Requests.

For the authentication: You need to implement the needed delegate methods for authentication yourself. Also check if you are connectiong through SSL and also implement the required delegate methods for this.

Edit: Heres a piece from one of my Apps that use HTTP auth. I discovered that you also need to return YES for the NSURLAuthenticationMethodHTTPBasic in the canAuthenticateAgainstProtectionSpace: method, otherwise it wont work.

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust] || [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodHTTPBasic];
}
花桑 2024-11-12 19:45:37

实现 NSURLConnection 委托方法:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
           NSLog("Connection successful");
   }

这将使用连接成功字符串记录到控制台。查看响应数据,您可能会在其中找到有关连接的一些信息。

Implement NSURLConnection delegate method :

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
           NSLog("Connection successful");
   }

This will log to the console with connection successful string. See the response data, you may find some information about the connection in it.

ぃ双果 2024-11-12 19:45:37

这是项目的代码

- (void)viewDidLoad {
    [super viewDidLoad];
    parserObject = [NSXML_Parser alloc];// parser initialization
    composerObject = [URLComposer alloc];// composer creation
    [composerObject init_URLComposer];//composer initialization

    [self.view addSubview:logIn_View];
    [webView1 loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"loginURl"]]];
    NSMutableData * receivedData = [NSMutableData alloc];
    NSLog(@"Starting the url conn");
    NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"loginURl"]                   
                                                cachePolicy:NSURLRequestUseProtocolCachePolicy                             
                                            timeoutInterval:60.0];
    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    [webView1 scalesPageToFit];
    if (theConnection) {

        receivedData = [[NSMutableData data] retain];

    } else {
        NSLog(@"Connection Failed");
        // Inform the user that the connection failed.
    }
}

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    NSURLRequest *urlreq =  [webView request];
    NSURL *req = [urlreq URL];
    NSURL *connectingUrl = [NSURL URLWithString: @"loginURl"];
    Boolean error1 = [req isEqual:errorUrl];// use string size to identify the error in url
    Boolean error2 = [req isEqual:connectingUrl];
    if (error1) {
        //[self.view addSubview:displayObj];
    }
    else if(error2) {

    }
    else {
        NSString *session_ID = [str_Url substringFromIndex:strLen];
        XMLDataFromServer = [NSData dataWithContentsOfURL:[NSURL  URLWithString:testing_Url_String]]; 
        [self logIn_Button_Click];
    }
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload {

}


- (void)dealloc {
    [super dealloc];
}

#pragma mark -
#pragma mark NSURLConnection Methods
#pragma mark -

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
    NSLog(@"canAuthenticateAgainstProtectionSpace");
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    if([challenge previousFailureCount] == 0){
        NSLog(@"Auth tried");
        NSURLCredential *credentials = [NSURLCredential credentialWithUser:@"userName" password:@"password" persistence:NSURLCredentialPersistenceNone];

        [[challenge sender] useCredential:credentials forAuthenticationChallenge:challenge];
    }
    else {
        NSLog(@"Auth failed");
    }    
}

- (void)connection:(NSURLConnection *)conn didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"didReceiveResponse: %@\n",[[response URL] absoluteString]);
}
- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data
{
    //NSLog(@"Did receive data: %@",data);
}

- (void)connection:(NSURLConnection *)conn didFailWithError:(NSError *)error
{

    NSLog(@"Error is:%@",error);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)conn
{

    NSLog(@"connectionDidFinishLoading");
}

Here is the code for project

- (void)viewDidLoad {
    [super viewDidLoad];
    parserObject = [NSXML_Parser alloc];// parser initialization
    composerObject = [URLComposer alloc];// composer creation
    [composerObject init_URLComposer];//composer initialization

    [self.view addSubview:logIn_View];
    [webView1 loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"loginURl"]]];
    NSMutableData * receivedData = [NSMutableData alloc];
    NSLog(@"Starting the url conn");
    NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"loginURl"]                   
                                                cachePolicy:NSURLRequestUseProtocolCachePolicy                             
                                            timeoutInterval:60.0];
    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    [webView1 scalesPageToFit];
    if (theConnection) {

        receivedData = [[NSMutableData data] retain];

    } else {
        NSLog(@"Connection Failed");
        // Inform the user that the connection failed.
    }
}

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    NSURLRequest *urlreq =  [webView request];
    NSURL *req = [urlreq URL];
    NSURL *connectingUrl = [NSURL URLWithString: @"loginURl"];
    Boolean error1 = [req isEqual:errorUrl];// use string size to identify the error in url
    Boolean error2 = [req isEqual:connectingUrl];
    if (error1) {
        //[self.view addSubview:displayObj];
    }
    else if(error2) {

    }
    else {
        NSString *session_ID = [str_Url substringFromIndex:strLen];
        XMLDataFromServer = [NSData dataWithContentsOfURL:[NSURL  URLWithString:testing_Url_String]]; 
        [self logIn_Button_Click];
    }
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload {

}


- (void)dealloc {
    [super dealloc];
}

#pragma mark -
#pragma mark NSURLConnection Methods
#pragma mark -

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
    NSLog(@"canAuthenticateAgainstProtectionSpace");
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    if([challenge previousFailureCount] == 0){
        NSLog(@"Auth tried");
        NSURLCredential *credentials = [NSURLCredential credentialWithUser:@"userName" password:@"password" persistence:NSURLCredentialPersistenceNone];

        [[challenge sender] useCredential:credentials forAuthenticationChallenge:challenge];
    }
    else {
        NSLog(@"Auth failed");
    }    
}

- (void)connection:(NSURLConnection *)conn didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"didReceiveResponse: %@\n",[[response URL] absoluteString]);
}
- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data
{
    //NSLog(@"Did receive data: %@",data);
}

- (void)connection:(NSURLConnection *)conn didFailWithError:(NSError *)error
{

    NSLog(@"Error is:%@",error);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)conn
{

    NSLog(@"connectionDidFinishLoading");
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文