很多应用都涉及到 网络连接部分。主要的网络连接方式有两种,一种是 http连接,一种是 socket连接。
http 连接 是 无状态连接。
维基百科的解释简单来说就是,通常,由HTTP客户端发起一个请求,建立一个到服务器指定端口(默认是80端口)的TCP连接。HTTP服务器则在那个端口监听客户端的请求。一旦收到请求,服务器会向客户端返回一个状态,比如"HTTP/1.1 200 OK",以及返回的内容,如请求的文件、错误消息、或者其它信息。
现在似乎还有http 持久连接,这个稍后再说。
socket 状态连接
socket 连接 按照我的理解则是 一种基于流 和进程 的连接,具有持久性,随着进程的运行而持续连接,等于在客户端与服务端间建立了一道桥梁保证他们之间的运输。
下面就来说说在ios 中如何 通过http连接 来跟 服务器间 传送数据。
思路 是 通过ios 自带的 nsmutalberequest 来完成的。
以下是一些代码:(同步http post请求,即在请求返回前会阻塞当前线程)
/**
* @name request
* @pam1 urlString:the url of the query's destination
* @pam2 dict:to format the post array of the http .
* @result return a NSDictionary contains the data what the protocol wo agree to.
**/
-(NSDictionary *)request:(NSString *)urlString dict:(NSDictionary *)dict{
NSDictionary *response = [[NSDictionary alloc] init];
NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//create a request for the http-query.
//And we set the request type to ignorecache to confirm each time we invoke this function,we
//acquire the latest data .
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:3.0f ];
//format the post array
// NSLog(@"ccccc");
NSMutableData *postData = [[NSMutableData alloc] init];
int l = [dict count];
NSArray *arr = [dict allKeys];
for (int i = 0 ; i < l ; ++i) {
if(i > 0 ){
NSString *temp = @"&";
[postData appendData:[temp dataUsingEncoding:NSUTF8StringEncoding]];
}
NSString *key = [arr objectAtIndex:i];
NSString *param = [dict objectForKey:key];
NSString *params = [[NSString alloc]initWithFormat:@"%@=%@",key,param];
[postData appendData:[params dataUsingEncoding:NSUTF8StringEncoding]];
}
//NSString *param = @"123=abc";
//[postData appendData:[param dataUsingEncoding:NSUTF8StringEncoding]];
//set http method and body.
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData];
//start the connnection and block the thread.
NSError *error;
NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
//create the NSDictionary from the json result.
response = [NSJSONSerialization JSONObjectWithData:received options:NSJSONReadingMutableContainers error:&error];
//just for Log.
NSString *str1 = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];
return response;
}
如果大家觉得有用欢迎复制粘贴使用,不过最好注释注明一下就好了。
NSDictionary *response = [[NSDictionary alloc] init];
NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
这部分是建立返回值的字典以及 将获取的 url字符串进行编码,防止中文、空格等非url标准字符的出现。
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:3.0f ];
//format the post array
NSMutableData *postData = [[NSMutableData alloc] init];
建立一个nsmutableurlrequest,cachepolicy的意思是当request 重新加载时,忽略 服务器 缓存的 data,保证每次 通过http 连接的 获取的data都是服务器上最新的data(会增加 相应的响应时间),timeoutinterval:则是 http 包超时的时间。
postData则是 http连接 包的body部分。
int l = [dict count];
NSArray *arr = [dict allKeys];
for (int i = 0 ; i < l ; ++i) {
if(i > 0 ){
NSString *temp = @"&";
[postData appendData:[temp dataUsingEncoding:NSUTF8StringEncoding]];
}
NSString *key = [arr objectAtIndex:i];
NSString *param = [dict objectForKey:key];
NSString *params = [[NSString alloc]initWithFormat:@"%@=%@",key,param];
[postData appendData:[params dataUsingEncoding:NSUTF8StringEncoding]];
}
讲传进来的post 参数 加入到http body中。
说实话,这个问题当初花了我几个小时来解决。网上很多教程 都只是说了post 数据 的时候 怎么传递一个参数。(可能都是聪明的人写的所以他们对这个理解很通透了吧)。作为刚刚出道的菜逼和水逼,我反正是鼓弄了半天没有成功传递参数,ios文档里面也没有很多关于nsmutablerequest的方法。网上多数使用的都是一个叫asihttprequest的第三方库,大家也可以尝试试下那个东西。
最后,我是查阅了http 连接 包里的 内容才 解决这个问题的。post数据是 http包body里的内容 ,如果是要传递多个参数则通过 &符号来进行分隔。我们继续看代码。
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData];
//start the connnection and block the thread.
NSError *error;
NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
最后一句 是 创建一个同步请求。returnresponse一个nsdata类型的应用,实际上我并没有用到(之后再补充吧)。
response = [NSJSONSerialization JSONObjectWithData:received options:NSJSONReadingMutableContainers error:&error];
//just for Log.
NSString *str1 = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];
// NSLog(@"%@",str1);
//NSLog(@"dict %d",[response count]);
return response;
现在服务器 返回数据一般采用json格式,json是一种比xml更轻量级的传输格式。第一句是将 json格式转成一个nsdictionary。
第二句则是 将 返回的nsdata转成nsstring 方便输出。
教程到这里就这么结束了,希望能给自己带来一些积累之余也能给大家带来便利,谢谢。
(之后有空还会分享 post 怎么样传数组,初步的 思路是在客户端先以json格式传参)。