IOS中http请求数据的解析以及http状态码的获取

一、http协议:

状态代码的第一位数字定义了回应的类别,后面两位数字没有具体分类。首位数字有5 
种取值可能: 
o 1xx::保留,将来使用。 
o 2xx:成功 - 操作被接收、理解、接受(received, understood, accepted)。 
o 3xx:重定向(Redirection)-要完成请求必须进行进一步操作。 
o 4xx:客户端出错 - 请求有语法错误或无法实现。 
o 5xx:服务器端出错 -服务器无法实现合法的请求。 
HTTP/1.0的状态代码、原因解释在下面给出。下面的原因解释只是建议采用,可任意 
更改,而不会对协议造成影响。完整的代码定义在第9节。 
       Status-Code    = "200"   ; OK 
                      | "201"   ; Created 
file:///C|/Documents and Settings/Administrator/桌面/HTTP RFC文档中文版.txt(第 18/30 页)2010-1-17 16:13:48
file:///C|/Documents and Settings/Administrator/桌面/HTTP RFC文档中文版.txt 
                      | "202"   ; Accepted 
                      | "204"   ; No Content 
                      | "301"   ; Moved Permanently 
                      | "302"   ; Moved Temporarily 
                      | "304"   ; Not Modified 
                      | "400"   ; Bad Request 
                      | "401"   ; Unauthorized 
                      | "403"   ; Forbidden 
                      | "404"   ; Not Found 
                      | "500"   ; Internal Server Error 
                      | "501"   ; Not Implemented 
                      | "502"   ; Bad Gateway 
                      | "503"   ; Service Unavailable 

                      | extension-code


二、状态码的获取

同步访问时的取法

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]);

    }
}

三、关键句

[response statusCode]

 

你可能感兴趣的:(网络相关)