Objective c 当需要XML时,NSURLConnection返回null
我有一个basecamp帐户,我正试图通过它的XMLAPI访问它 我已经创建了一个带有正确头字段的NSURL请求Objective c 当需要XML时,NSURLConnection返回null,objective-c,cocoa,Objective C,Cocoa,我有一个basecamp帐户,我正试图通过它的XMLAPI访问它 我已经创建了一个带有正确头字段的NSURL请求 NSURL* projectsUrl = [NSURL URLWithString:[self.accountURL stringByAppendingString:@"/projects.xml"]]; NSMutableURLRequest* projectsRequest = [NSMutableURLRequest requestWithURL:project
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];
}
}
问题是,即使在使用正确的url、身份验证凭据和标题字段之后,我在
responseData
中也会得到null
数据,而当我尝试使用curl
访问同一url时,我会从basecamp服务器得到正确的xml响应。我对目标C还不熟悉。请解释并告诉我,我还应该做些什么来实现这一目标 是否确实设置了[self-responseData]
?尝试使用相同的URL和,看看是否有效。在启动连接之前([connection start];
)应该初始化属性responseData
,例如,self.responseData=[[NSMutableData alloc]init]代码>
在方法-(void)connection:(NSURLConnection*)conn didReceiverResponse:(nsurResponse*)response
中,应将该数据的长度设置为零:[self.responseData setLength:0]代码>是的,我用代码[[self-responseData]appendData:data]附加它;在didReceiveData方法中,能否将代码粘贴到初始化它的位置?例如,[self-setResponseData:[NSMutableData data]]您是否启动了responseData
?是的,初始化responseData有效。非常感谢。我的朋友,如果你觉得我的评论对你有帮助,请投票:将回应的数据拼音化有效。此外,为什么要将其长度设置为零?因为此方法可以多次调用。您只需要在最后一次呼叫后存储数据。@Anand:进一步说明Nekto的评论,对于URL重定向之类的内容,您将获得多个didReceiveResponse:
呼叫,可能会收到一些数据,但是,当收到最终HTTP响应时,应该放弃此操作,因为之前的数据实际上不是加载的最终页面的一部分。谢谢@darvids0n!这就是我的意思,因为HttpRequest非常棒。我刚查过。有些事情真的很容易。
-(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];
}