您的位置:首页 > 理论基础 > 计算机网络

[iOS 多线程 & 网络 - 2.0] - 发送接收 服务器信息

2015-01-25 20:47 267 查看
A.搭建java服务器
使用eclipse、tomcat和struts2框架搭建一个简单的服务器
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,注意配置正确的服务器的路径和发布路径,不要使用默认的eclipse中的路径
6.引入资源文件,创建相应的ActionSupport就可以处理外部信息了

server source: https://github.com/hellovoidworld/MyOnlineVideoDemoServer

B.iOS中基本的服务器请求
1.get和post
GET和POST是两种最常用的与服务器进行交互的HTTP方法
GET
GET的语义是获取指定URL的资源
将数据按照variable=value的形式,添加到action所指向的URL后面,并且两者使用"?"连接,各变量之间使用"&"连接
貌似不安全,因为在传输过程中,数据被放在请求的URL中
传输的数据量小,这主要是因为受URL长度限制





POST
POST的语义是向指定URL的资源添加数据
将数据放在数据体中,按照变量和值相对应的方式,传递到action所指向URL
所有数据对用户来说不可见
可以传输大量数据,上传文件只能使用Post





C.iOS发送网络请求
1.发送步骤
实例化URL(网络资源)
根据URL建立URLRequest(网络请求)
默认为GET请求
对于POST请求,需要创建请求的数据体
利用URLConnection发送网络请求(建立连接)
获得结果

NSURLConnection提供了两个静态方法可以直接以同步或异步的方式向服务器发送网络请求
同步请求:
sendSynchronousRequest:returningResponse:error:
异步请求:
sendAsynchronousRequest:queue: completionHandler:

2.网络传输中的二进制流
在网络请求过程中,接收数据的过程实际上是通过NSURLConnectionDataDelegate来实现的,常用代理方法包括:

服务器开始返回数据,准备工作
(void)connection:didReceiveResponse:
收到服务器返回的数据,本方法会被调用多次
- (void)connection:didReceiveData:
数据接收完毕,做数据的最后处理
(void)connectionDidFinishLoading:
网络连接错误
- (void)connection:didFailWithError:

D.练习代码




1.使用get请求

(1).使用同步方法发送get请求(不常用)
/** 发送get消息 */
- (void) testGet {
NSString *requestStr = [NSString stringWithFormat:@"http://192.168.0.21:8080/MyTestServer/login?user=%@&password=%@", self.userField.text, self.passwordField.text];

NSURL *url = [NSURL URLWithString:requestStr];

// 默认就是get请求
NSURLRequest *request = [NSURLRequest requestWithURL:url];

// 使用同步方法发送请求
[self sendSynRequest:request];
}

/** 同步发送请求 */
- (void) sendSynRequest:(NSURLRequest *) request {
// 同步发送信息
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

[self dealWithResponseData:data];
}

/** 处理返回数据 */
- (void) dealWithResponseData:(NSData *) data {
// 解析数据
if (data) { // 得到返回数据
// 解除屏幕锁
[MBProgressHUD hideHUD];

// 解析json数据
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];

// 处理返回的数据
NSString *result = dict[@"success"];
if (result) {
[MBProgressHUD showSuccess:result];
} else {
result = dict[@"error"];
if (result) {
[MBProgressHUD showError:result];
}
}
} else {
[MBProgressHUD showError:@"网络繁忙,请稍后再试~"];
}
}


(2).使用异步方法发送get请求

/** 异步发送请求 */
- (void) sendAsynRequest:(NSURLRequest *) request {
NSOperationQueue *queue = [NSOperationQueue mainQueue];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

[self dealWithResponseData:data];
}];
}


2.使用NSURLConnectionDataDelegate代理发送异步请求
(1)遵守协议

@interface ViewController () <NSURLConnectionDataDelegate>


(2)设置代理、发送请求

/** 使用start & 代理发送、处理异步请求 */
- (void) sendAsynRequestWithDelegate:(NSURLRequest *) request {
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
[connection start];
}


(3)实现代理方法

#pragma mark - NSURLConnectionDataDelegate 代理方法
/** 收到服务器回应 */
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(@"didReceiveResponse");
self.data = [NSMutableData data];
}

/** 接收到的数据,会调用多次,数据被分割接收 */
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(@"didReceiveData");
[self.data appendData:data];
}

/** 接收数据完毕 */
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"connectionDidFinishLoading");
[self dealWithResponseData:self.data];
}


3.使用post请求

#pragma mark - post
- (void) testPost {
NSString *requestStr = [NSString stringWithFormat:@"http://192.168.0.21:8080/MyTestServer/login"];
NSURL *url = [NSURL URLWithString:requestStr];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.timeoutInterval = 5;

// 设置为post方式请求
request.HTTPMethod = @"POST";

// 设置请求头
[request setValue:@"ios" forHTTPHeaderField:@"User-Agent"];

// 设置请求体
NSString *param = [NSString stringWithFormat:@"user=%@&password=%@", self.userField.text, self.passwordField.text];
request.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding];

// 发送请求
// 使用主线程来处理UI刷新
NSOperationQueue *queue = [NSOperationQueue mainQueue];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
[self dealWithResponseData:data];
}];

}


4.设置请求属性
(1)设置超时时限

// 使用可变request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 设置请求超时时间
request.timeoutInterval = 5;


4.中文转码
使用UTF8转码
[urlStr stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];

NSString *requestStr = [NSString stringWithFormat:@"http://192.168.0.21:8080/MyTestServer/login?user=%@&password=%@", self.userField.text, self.passwordField.text];

// 由于url不能传送中文,所以需要转码
requestStr = [requestStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐