2011-09-12 257 views
1

我有一個basecamp帳戶,我試圖通過它的XML API訪問。當預期XML時,NSURLConnection返回null

我已經創建了一個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]; 

} 

的問題是,即使使用正確的網址,認證證書和標頭字段後,我得到了responseDatanull數據,而當我嘗試用curl我從大本營服務器正確的XML響應訪問同一個網址。我是新來的客觀的C.請解釋並告訴我還有什麼我應該設置得到這個權利。

+0

你開始'responseData'? – Scar

+0

雅,初始化responseData工作。非常感謝 – Anand

+0

wel。我的朋友,如果你覺得我的評論對你有幫助,請投票:P – Scar

回答

2

在開始連接之前([connection start];),您應該初始化屬性responseData,例如,self.responseData = [[NSMutableData alloc] init];

在方法- (void)connection:(NSURLConnection *)conn didReceiveResponse:(NSURLResponse *)response你應該設置這些數據的零長度:[self.responseData setLength:0];

+0

啓動responseData工作。此外,爲什麼我應該將其長度設置爲零? – Anand

+0

因爲這個方法可以被調用多次。只有在最後一次呼叫後才需要存儲數據。 – Nekto

+2

@Anand:對於Nekto的評論,對於像URL重定向這樣的事情,您會得到多個'didReceiveResponse:'調用,可能會收到一些數據,但是當收到最終的HTTP響應時應該丟棄它,因爲此前的數據不是實際上是加載的最終頁面的一部分。 – darvids0n

1

您確定您設置了[self responseData]

+0

是的,我附加了這個代碼[[self responseData] appendData:data];在didReceiveData方法中 – Anand

+0

您可以將代碼粘貼到哪裏嗎? 例如,[self setResponseData:[NSMutableData data]] –

0

嘗試使用與ASIHTTPRequest相同的網址,看看它是否有效。

+0

ASIHTTPRequest非常棒。剛剛檢查出來。有些事情確實很容易。 – Anand