我们可以通过NSMutableURLRequest 建立与服务器的链接,然后从服务器拉取数据。有必要认识一下几种类型。NSString 和 NSData 和 NSMutableData 是可以相互转换的。
一般情况下,我们用NSString 拼凑出NSData 然后发送请求,收到NSData然后收集到NSMutableData里面,最后再将NSMutableData进行解析,转变成我们常用的NSString。
生成请求的方法
NSString *RequestURL = [NSString stringWithFormat:@"http://192.168.1.15/test.html"]; NSURL *URLStr = [NSURL URLWithString:RequestURL]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:URLStr cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10]; [request setHTTPMethod:@"POST"]; cnt0 = [[NSURLConnection alloc]initWithRequest:request delegate:self];
里面的delegate 十分重要,不delegate 将无法接收数据。
在 interface 里面声明数据集
@property (strong,nonatomic) NSMutableData *receiveData0;
其中 cnt0应该在.m文件的implementation 后面马上定义
@implementation mcViewController NSURLConnection *cnt0; - (void)viewDidLoad{ [super viewDidLoad]; [_mywebview setDelegate:self]; // Do any additional setup after loading the view, typically from a nib. }
如果需要POST里面含有数据,可以添加HTTPBody
NSString *str = @""; NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding]; [request setHTTPBody:data];
下面是几个delegate 的事件
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{ if (connection==cnt0) { //NSHTTPURLResponse *res = (NSHTTPURLResponse *)response; _receiveData0 = [NSMutableData data]; } } -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ if (connection==cnt0) { [self.receiveData0 appendData:data]; NSLog(@"loading"); } } -(void)connectionDidFinishLoading:(NSURLConnection *)connection{ if (connection==cnt0) { NSURL *thisurl = [NSURL URLWithString:@"http://192.168.1.15/"]; NSString *content = [[NSString alloc]initWithData:_receiveData0 encoding:NSUTF8StringEncoding]; [_mywebview loadHTMLString:content baseURL:thisurl]; NSLog(@"Finished"); } }
很多网站的API用的都是API,我们可以通过对应的方法对数据进行解析。
NSDictionary *data = [NSJSONSerialization JSONObjectWithData:_receiveData1 options:NSJSONReadingMutableLeaves error:nil]; NSLog(@"%@",[data objectForKeyedSubscript:@"query"]); NSArray *thelist = [[[[data objectForKeyedSubscript:@"query"] objectForKey:@"pages"] objectForKey:@"78862"] objectForKey:@"revisions"]; NSDictionary *getfinal = [thelist objectAtIndex:0]; NSLog(@"%@",[getfinal objectForKey:@"*"]);