网页浏览总次数

2011年5月19日星期四

转---iPhone开发:通过NSURLRequest获得服务器返回的http header和http status

同步访问时的取法
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",[responsestatusCode]);

   }
}

没有评论:

发表评论