JCDHTTPConnection是对NSURLConnection的轻量级包装,它提供了一个简单的块回调API。
JCDHTTPConnection对象使用NSURLRequest对象初始化,然后在连接上调用executeRequestOnSuccess:failure:didSendData以初始化异步请求。三个回调块:onSuccess、onFailure和onDidSendData都是可选的。
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://apple.com"]];
JCDHTTPConnection *connection = [[JCDHTTPConnection alloc] initWithRequest:request];
[connection executeRequestOnSuccess:
^(NSHTTPURLResponse *response, NSString *bodyString) {
NSLog(@"SUCCESS: %d: %@", response.statusCode, bodyString);
} failure:^(NSHTTPURLResponse *response, NSString *bodyString, NSError *error) {
NSLog(@"FAILURE: %@", error);
} didSendData:^(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite) {
// This is not going to be called in this example but it's included for completeness.
NSLog(@"DID SEND DATA: %d", bytesWritten);
}];
仓库中包含一个示例Xcode项目,该项目可以获取URL并显示响应。