当期望XML时,NSURLConnection返回null

时间:2011-09-12 05:45:32

标签: objective-c cocoa

我有一个我想通过其XML API访问的basecamp帐户。

我创建了一个带有正确标头字段的NSURL请求。

    NSURL* projectsUrl = [NSURL URLWithString:[self.accountURL stringByAppendingString:@"/projects.xml"]];
    NSMutableURLRequest* projectsRequest = [NSMutableURLRequest requestWithURL:projectsUrl];

    [projectsRequest setValue:@"application/xml" forHTTPHeaderField:@"Content-Type"];
    [projectsRequest setValue:@"application/xml" forHTTPHeaderField:@"Accept"];

我创建一个连接并启动它。

    NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:projectsRequest delegate:self];
    [connection start];
    [connection autorelease];

Basecamp使用HTTP基本身份验证。所以我使用NSCredential对象来处理它,如下所示。

-(void) connection:(NSURLConnection*)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge*)authenticationChallenge
{


    if ([authenticationChallenge previousFailureCount] <=2 ) {
        NSURLCredential* basecampCredentials;
        basecampCredentials = [NSURLCredential credentialWithUser:[self username] 
                                                         password:[self password]
                                                      persistence:NSURLCredentialPersistenceNone];
        [[authenticationChallenge sender] useCredential:basecampCredentials forAuthenticationChallenge:authenticationChallenge];
    }else {
        [[authenticationChallenge sender] cancelAuthenticationChallenge:authenticationChallenge];

    }

}

当我从连接接收数据时,我会与这些代表一起处理它。

-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [[self responseData] appendData: data];
    NSLog(@"I received %@", [self responseData]);

}


-(void) connectionDidFinishLoading:(NSURLConnection*)connection
{
    NSLog(@"I FINALLY received %@", [self responseData]);

    NSXMLParser* parser = [[NSXMLParser alloc] initWithData:[self responseData]];
    [parser setDelegate:self];
    BOOL success = [parser parse];
    if (success) {
        NSLog(@"XML parse success");
    }else {
        NSLog(@"XML parse ERROR");
    }

    [parser autorelease];

}

问题是在使用正确的网址,身份验证凭据和标头字段后,我在null中获得了responseData数据,而当我尝试使用curl访问相同的网址时,我得到了正确的xml来自basecamp服务器的响应。我是客观C的新手。请解释并告诉我还应该设置什么才能做到这一点。

3 个答案:

答案 0 :(得分:2)

在开始连接([connection start];)之前,您应该初始化属性responseData,例如self.responseData = [[NSMutableData alloc] init];

在方法- (void)connection:(NSURLConnection *)conn didReceiveResponse:(NSURLResponse *)response中,您应该将该数据的长度设置为零:[self.responseData setLength:0];

答案 1 :(得分:1)

您确定要设置[self responseData]吗?

答案 2 :(得分:0)

使用ASIHTTPRequest尝试相同的网址,看看它是否有效。