一、基本步骤
1、创建URL字符串,即网址
2、创建URL,即创建一个需要请求的资源
3、创建一个请求
4、创建POST请求体
5、发起连接
6、接收数据
二、代码示例:[……]
一、基本步骤
1、创建URL字符串,即网址
2、创建URL,即创建一个需要请求的资源
3、创建一个请求
4、创建一个连接
5、发起连接
6、接收数据
二、代码示例:
1、实现网络请求
1 2 3 4 5 6 7 8 9 10 | // 1、创建URL字符串,即网址 NSString *string = @"www.baidu.com"; // 2、创建URL,即创建一个需要请求的资源 NSURL *url = [NSURL URLWithString:string]; // 3、创建一个请求 NSURLRequest *request = [NSURLRequest requestWithURL:url]; // 4、创建一个连接 NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self]; // 5、发起连接 [connection start]; |
2、实现代理方法接收数据,遵循
1、Get请求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | // Get请求 // 初始化网络引擎对象 MKNetworkEngine *engine = [[MKNetworkEngine alloc] initWithHostName:@"192.168.2.176:9502/api" customHeaderFields:nil]; // 创建一个Get请求 MKNetworkOperation *op = [engine operationWithPath:@"login.php?userid=admin&userpwd=123" params:nil httpMethod:@"GET"]; // 设置Get请求处理方式 [op onCompletion:^(MKNetworkOperation *operation){ // 请求成功 NSLog(@"request string: %@",[operation responseString]); } onError:^(NSError *error){ // 请求失败 NSLog(@"%@", error); }]; // 入列操作(发起网络请求) [engine enqueueOperation:op]; |
2、Post请求[……]
一、UIWebView 可以加载和显示某个URL的网页,也可以显示基于HTML的本地网页或部分网页:
a. 加载 URL
1 2 3 4 | WebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 44, 320, 400)]; NSString *path = @"http://www.baidu.com"; NSURL *url = [NSURL URLWithString:path]; [WebView loadRequest:[NSURLRequest requestWithURL:url]]; |
b. 加载 HTML
1 2 3 4 5 | NSBundle *bundle = [NSBundle mainBundle]; NSString *resPath = [bundle resourcePath]; NSString *filePath = [resPath stringByAppendingPathComponent:@"Home.html"]; [webView loadHTMLString:[NSString stringWithContentsOfFile:filePath] baseURL:[NSURL fileURLWithPath:[bundle bundlePath]]]; |
二、使用网页加载指示,加载完成后再显示网页出来
首先要指定委托方法:
webView.delegate =self;
UIWebView主要有下面几个委托方法:
1 2 3 | - (void)webViewDidStartLoad:(UIWebView *)webView;开始加载的时候执行该方法。 - (void)webViewDidFinishLoad:(UIWebView *)webView;加载完成的时候执行该方法。 - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error;加载出错的时候执行该方法。 |
这样,可以利用 webViewDidStartLoad 和 webViewDidFinishLoad 方法实现本功能:[……]
在进行网络请求时出现-1016 是因为只支持text/json,application/json,text/javascript
你可以添加text/html,一劳永逸的方法是在AFURLResponseSerialization.h里面搜索self.acceptableContentTypes然后[……]