iOS 网络编程 (1)-解析URL,提取数据

来源:互联网 发布:java中链表 编辑:程序博客网 时间:2024/05/01 03:31
通过网络获取数据有两种方法: 1.使用NSURL类的方法NSURLConnection 和 NSURLRequest;2.使用NSData 的方法initContentWithURL 或 dataWithContentsOfURL。

方法一:
     NSString *googleURL = @"http://www.weather.com.cn/data/cityinfo/10107101.html";
    NSURL *url = [NSURL URLWithString: googleURL];
     NSURLRequest *request = [[NSURLRequest alloc] initWithURL: url];
     NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest delegate: self];
     
     什么是URL?

     首先,我们必须知道 URL, URL全称为 UniformResourceLocator, 统一资源定位符,也即网址。
     网址的形式一般为: <URL的访问方式>:// <主机>:<端口>/<路径>。
     URL的访问方式: ftp (文件传送协议),http(超文本传送协议),News (USENET USENET新闻)。
    
      为什么要使用 NSURL?

     网址是一个字符串,为什么要转换成NSURL的对象呢?因为网址的字符串都比较复杂,包括很多的请求参数,如此一来,在请求的过程中要解析出来每一个部分,所以要封装一个NSURL。
例如:
     NSURL *url = [NSURL URLWithString: @"http: // www.baidu.com/s? tn=baiduhome_pg&bs = NSURL&f = 8&rsv_bp = 1&rsv_spt = 1&wd = NSurl&inputT = 2709"];
     NSLog(@"Scheme : %@", [url scheme]); scheme - 计划
     NSLog(@"host : %@", [ url host]); host - 主机
     NSLog 、、、                                port - 端口
     、、、                                            path
     、、、                                            relativePath
     、、、                                            pathComponent
     、、、                                            parameterString - 参数字符串
     、、、                                            query - 疑问
     、、、                                            fragment - 碎片, 不完整的部分
     、、、                                            user
     、、、                                            password
输出的结果:
     scheme: http
     host: www.baidu.com
     port: (null)
     path: /s
     relativePath: /s
     path components as array: ("/",s)
     parameterString: (null)
     query: tn = baiduhome  ,,,   = 2709
     fragment: (null)
     user: (null)
     password:(null)

     为什么要使用 NSURLRequest ?

     所构建的 NSURLRequest 具有一个依赖于缓存响应的特定策略,cachePolicy 取得策略,
timeoutInterval 取得超时值。
    
     例如:
     NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString: @"http://www.apple.com/"] cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 50.0];
     
     // creating the connection with the request
     // and start loading the data
     NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest: theRequest delegate: self];

     if (theConnection) {
          // creating the NSMutableData to hold the receive data 
          // receivedData is an instance variable declared elsewhere
     receivedData = [[NSMutableData data] retain];
     }else{
          // inform the user the connection is failed
     }



     委托的处理方法

     -(void) connection : (NSURLConnection *) connection didReceiveData: (NSData *) data{
          outString = [[ NSStirng alloc ] initWithData: data encoding: NSUTF8StringEncoding];
          NSLog(@"%@", outString);
     }

     -(void) connection: (NSURLConnection *) connection didFailWithError: (NSError *)error{
     ,          ,          ,       
     }
     -(void) connectionDidFinishLoading: (NSURLConnection *) connection{
       ,          ,          ,
    }


     方法2:

#define KWeatherServiceURLStr @"http:// webserive.webxml.com.cn/WebServices/WeatherWebService.asmx/getWeatherbyCityName?"


   NSString *RequestUrlStr = [NSString stringWithFormat:@"%@%@", KWeatherServiceURLStr,[[ipCityLocationcitySimpleName]stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];   
   NSLog(@"request = %@", RequestUrlStr);   
   NSData *responseData = [NSData dataWithContentsOfURL:[NSURL URLWithString:RequestUrlStr]];
    

     第二部分 在获取了数据以后把数据解析(使用了第三方库)

        // 使用第三方库 TouchJson
    // 获取 API    
    NSURL *url = [NSURL URLWithString:@"www.weather.com.cn/data/sk/101010100.html"];    
    // 定义一个 NSError 对象, 用于捕获错误信息    
    NSError *error;    
    NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];     // 将解析后的数据放到字典中,编码格式为 UTF8    
    NSDictionary *rootDic = [[CJSONDeserializer deserializer] deserialize:[jsonStringdataUsingEncoding: NSUTF8StringEncoding] error: &error];    
    // 返回的Json 文件有两层,取第二层的内容到字典中    
    NSDictionary *weatherInfo = [rootDic objectForKey:@"weatherinfo"];    
    // 取值输出    
    NSLog(@"Today is %@%@%@ .The condition of weather is %@%@",[weatherInfo objectForKey:@"date_y"], [weatherInfo objectForKey:@"week"], [weatherInfo objectForKey:@"city"], [weatherInfo objectForKey:@"weather1"], [weatherInfo objectForKey:@"temp1"]);


 今天 google 了好多关于 解析URL的内容,这块内容大体有了一定的了解,把整理的内容与大家分享哈 :)









0 0
原创粉丝点击