iOS多线程与网络开发之发送接收server信息

郝萌主倾心贡献,尊重作者的劳动成果,请勿转载。

假设文章对您有所帮助,欢迎给作者捐赠。支持郝萌主,捐赠数额任意,重在心意^_^ 

我要捐赠: 点击捐赠

Cocos2d-X源代码下载:点我传送

游戏官方下载:http://dwz.cn/RwTjl

游戏视频预览:http://dwz.cn/RzHHd

游戏开发博客:http://dwz.cn/RzJzI

游戏源代码传送http://dwz.cn/Nret1


A.搭建javaserver
使用eclipse、tomcat和struts2框架搭建一个简单的server
1.准备好合适版本号的JDK、eclipse EE、tomcat、struts2 框架包
2.配置JDK和tomcat系统变量
3.在eclipse中创建一个Dynamic Web Project, 勾选创建web.xml
4.解压一个struts2中的app范例。參考当中的web.xml和struts.xml配置
5.配置tomcat。注意配置正确的server的路径和公布路径。不要使用默认的eclipse中的路径
6.引入资源文件,创建相应的ActionSupport就能够处理外部信息了
  
B.iOS中主要的server请求
1.get和post
GET和POST是两种最经常使用的与server进行交互的HTTP方法
GET
GET的语义是获取指定URL的资源
将数据依照variable=value的形式,加入到action所指向的URL后面,而且两者使用"?

"连接。各变量之间使用"&"连接
貌似不安全。由于在传输过程中。数据被放在请求的URL中

传输的数据量小,这主要是由于受URL长度限制
 
Image(38)
 
POST
POST的语义是向指定URL的资源加入数据
将数据放在数据体中,依照变量和值相相应的方式,传递到action所指向URL
全部数据对用户来说不可见
能够传输大量数据,上传文件仅仅能使用Post
 
Image(39)
 
C.iOS发送网络请求
1.发送步骤
实例化URL(网络资源)
依据URL建立URLRequest(网络请求)
默觉得GET请求
对于POST请求。须要创建请求的数据体
利用URLConnection发送网络请求(建立连接)
获得结果

NSURLConnection提供了两个静态方法能够直接以同步或异步的方式向server发送网络请求
同步请求:
sendSynchronousRequest:returningResponse:error:
异步请求:
sendAsynchronousRequest:queue: completionHandler:
 
2.网络传输中的二进制流
在网络请求过程中,接收数据的过程实际上是通过NSURLConnectionDataDelegate来实现的,经常使用代理方法包含:

server開始返回数据,准备工作
(void)connection:didReceiveResponse:
收到server返回的数据。本方法会被调用多次
- (void)connection:didReceiveData:
数据接收完成,做数据的最后处理
(void)connectionDidFinishLoading:
网络连接错误
- (void)connection:didFailWithError:
 
D.练习代码
NetworkRequest
 
1.使用get请求
 11).使用同步方法发送get请求(不经常使用)
 2 /** 发送get消息 */
 3 - (void) testGet {
 4     NSString *requestStr = [NSString stringWithFormat:@"http://192.168.0.21:8080/MyTestServer/login?

user=%@&password=%@", self.userField.text, self.passwordField.text]; 5 6 NSURL *url = [NSURL URLWithString:requestStr]; 7 8 // 默认就是get请求 9 NSURLRequest *request = [NSURLRequest requestWithURL:url]; 10 11 // 使用同步方法发送请求 12 [self sendSynRequest:request]; 13 } 14 15 /** 同步发送请求 */ 16 - (void) sendSynRequest:(NSURLRequest *) request { 17 // 同步发送信息 18 NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; 19 20 [self dealWithResponseData:data]; 21 } 22 23 /** 处理返回数据 */ 24 - (void) dealWithResponseData:(NSData *) data { 25 // 解析数据 26 if (data) { // 得到返回数据 27 // 解除屏幕锁 28 [MBProgressHUD hideHUD]; 29 30 // 解析json数据 31 NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil]; 32 33 // 处理返回的数据 34 NSString *result = dict[@"success"]; 35 if (result) { 36 [MBProgressHUD showSuccess:result]; 37 } else { 38 result = dict[@"error"]; 39 if (result) { 40 [MBProgressHUD showError:result]; 41 } 42 } 43 } else { 44 [MBProgressHUD showError:@"网络繁忙。请稍后再试~"]; 45 } 46 }

复制代码
 
(2).使用异步方法发送get请求
1 /** 异步发送请求 */
2 - (void) sendAsynRequest:(NSURLRequest *) request {
3     NSOperationQueue *queue = [NSOperationQueue mainQueue];
4     [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
5        
6         [self dealWithResponseData:data];
7     }];
8 }
复制代码
 
2.使用NSURLConnectionDataDelegate代理发送异步请求
(1)遵守协议
1 @interface ViewController () <NSURLConnectionDataDelegate>
 
(2)设置代理、发送请求
1 /** 使用start & 代理发送、处理异步请求 */
2 - (void) sendAsynRequestWithDelegate:(NSURLRequest *) request {
3     NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
4     [connection start];
5 }
 
(3)实现代理方法
 1 #pragma mark - NSURLConnectionDataDelegate 代理方法
 2 /** 收到server回应 */
 3 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
 4     NSLog(@"didReceiveResponse");
 5     self.data = [NSMutableData data];
 6 }
 7 
 8 /** 接收到的数据,会调用多次,数据被切割接收 */
 9 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
10     NSLog(@"didReceiveData");
11     [self.data appendData:data];
12 }
13 
14 /** 接收数据完成 */
15 - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
16     NSLog(@"connectionDidFinishLoading");
17     [self dealWithResponseData:self.data];
18 }
 
 
3.使用post请求
 1 #pragma mark - post
 2 - (void) testPost {
 3     NSString *requestStr = [NSString stringWithFormat:@"http://192.168.0.21:8080/MyTestServer/login"];
 4     NSURL *url = [NSURL URLWithString:requestStr];
 5    
 6     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
 7     request.timeoutInterval = 5;
 8    
 9     // 设置为post方式请求
10     request.HTTPMethod = @"POST";
11    
12     // 设置请求头
13     [request setValue:@"ios" forHTTPHeaderField:@"User-Agent"];
14    
15     // 设置请求体
16     NSString *param = [NSString stringWithFormat:@"user=%@&password=%@", self.userField.text, self.passwordField.text];
17     request.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding];
18    
19     // 发送请求
20     // 使用主线程来处理UI刷新
21     NSOperationQueue *queue = [NSOperationQueue mainQueue];
22     [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
23         [self dealWithResponseData:data];
24     }];
25   
26 }
 
 
4.设置请求属性
(1)设置超时时限
1     // 使用可变request
2     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
3     // 设置请求超时时间
4     request.timeoutInterval = 5;
 
4.中文转码
使用UTF8转码
[urlStr stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
1     NSString *requestStr = [NSString stringWithFormat:@"http://192.168.0.21:8080/MyTestServer/login?user=%@&password=%@", self.userField.text, self.passwordField.text];
2    
3     // 由于url不能传送中文,所以须要转码
4     requestStr = [requestStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
 

郝萌主倾心贡献,尊重作者的劳动成果,请勿转载。

假设文章对您有所帮助,欢迎给作者捐赠,支持郝萌主,捐赠数额任意,重在心意^_^ 

我要捐赠: 点击捐赠

Cocos2d-X源代码下载:点我传送

游戏官方下载:http://dwz.cn/RwTjl

游戏视频预览:http://dwz.cn/RzHHd

游戏开发博客:http://dwz.cn/RzJzI

游戏源代码传送http://dwz.cn/Nret1

原文地址:https://www.cnblogs.com/zsychanpin/p/6743902.html