我有一个basecamp帐户,我正试图通过它的XML API访问它。
我已经创建了一个具有正确报头字段的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];
}
}当我从connection接收数据时,我用这些委托来处理它。
-(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];
}问题是,即使在使用正确的url、身份验证凭据和报头字段之后,我也会在responseData中获得null数据,而当我尝试使用curl访问相同的url时,我会从basecamp服务器获得正确的xml响应。我是目标C的新手。请解释并告诉我我还应该设置什么才能正确完成这项任务。
发布于 2011-09-12 14:01:47
在启动连接([connection start];)之前,您应该初始化属性responseData,例如self.responseData = [[NSMutableData alloc] init];。
在方法- (void)connection:(NSURLConnection *)conn didReceiveResponse:(NSURLResponse *)response中,您应该将该数据的长度设置为零:[self.responseData setLength:0];
发布于 2011-09-12 13:51:41
您确定设置了[self responseData]吗
发布于 2011-09-12 13:53:50
使用ASIHTTPRequest尝试相同的URL,看看是否有效。
https://stackoverflow.com/questions/7383745
复制相似问题