同步访问时的取法
NSURL *url = [NSURL URLWithString:@"http://www.test.com"];
NSURLRequest *request = [NSURLRequest requestWithURL: url];
NSHTTPURLResponse *response;
[NSURLConnection sendSynchronousRequest: request returningResponse: &response error: nil];
if ([response respondsToSelector:@selector(allHeaderFields)]) {
// 取得所有的请求的头
NSDictionary *dictionary = [response allHeaderFields];
NSLog([dictionary description]);
// 取得http状态码
NSLog(@"%d",[response statusCode]);
}
异步访问时则要实现委托的一个方法
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// 注意这里将NSURLResponse对象转换成NSHTTPURLResponse对象才能去
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
if ([response respondsToSelector:@selector(allHeaderFields)]) {
NSDictionary *dictionary = [httpResponse allHeaderFields];
NSLog([dictionary description]);
NSLog(@"%d",[response statusCode]);
}
}