28

我需要检查和评估我的 iPhone 应用程序中的 HTTP 状态代码。我有一个 NSURLRequest 对象和一个 NSURLConnection 成功(我认为)连接到该站点:

// create the request
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.apple.com/"]
                        cachePolicy:NSURLRequestUseProtocolCachePolicy
                    timeoutInterval:60.0];
// create the connection with the request
// and start loading the data
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
    // Create the NSMutableData that will hold
    // the received data
    // receivedData is declared as a method instance elsewhere
    receivedData=[[NSMutableData data] retain];
} else {
    // inform the user that the download could not be made
}

我在这里得到了这个代码:https ://web.archive.org/web/20100908130503/http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html

但它(据我所知)并没有说明访问 HTTP 状态代码的任何内容。

如何建立与站点的连接,然后检查该连接的 HTTP 状态代码?

4

1 回答 1

76

我就是这样做的:

    #pragma mark -
    #pragma mark NSURLConnection Delegate Methods
    - (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response {
         NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
         int responseStatusCode = [httpResponse statusCode];
    }

但是我使用的是异步 NSURLConnection,所以这可能对你没有帮助。但我希望它无论如何!

于 2009-05-27T20:48:12.810 回答