iPhone应用用HTTP协议和服务器通信
iPhone应用用HTTP协议和服务器通信是本文要介绍的内容,主要是来学习iphone应用中的通信协议,具体内容来看本文详解。iPhone用http协议和服务器通信有两种方式,一种是同步一种是异步的,所谓同步是指当客户端调用post/get的方式的函数向服务器发出数据请求后,该函数不会直接返回,只有得到服务器响应或者请求时间timeout之后才会返回继续执行其它任务。异步采用回调的方式,即请求发送后,函数会立即返回,一旦服务器联结成功操作系统会去触发相应的回调进行相应的处理。这和window的消息处理机制一样。
同步一般用于一次性操作,如判断当前网络是否可用等等。多的就不再一一介绍,在实现上面有两点不同:
(1)在用NSURLConnect的时候一个调用同步函数一个调用了异步函数。
(2)异步的需要实现delegate的相关回调函数。
以下是参考代码:
同步方式:
[*]-(void)UpadaPost:(NSString *)strcontext URL:(NSString *)urlstr{
[*]NSLog(urlstr);
[*]NSLog(strcontext);
[*]assert(strcontext != NULL);
[*]assert(urlstr != NULL);
[*]NSData*postData=;
[*]NSString *postLength = ];
[*]NSMutableURLRequest *request = [[ init] autorelease];
[*]];
[*]; ;//setting timeout
[*];
[*];
[*];
[*]NSURLResponse *respone;
[*]NSError *error;
[*]NSData*myReturn=[NSURLConnectionsendSynchronousRequest:request returningResponse:&respone
[*]error:error];
[*]NSLog(@"%@", [ initWithData:myReturn encoding:NSUTF8StringEncoding]);
[*]}
异步方式:
[*]-(void)UpadaPost:(NSString *)strcontext URL:(NSString *)urlstr{
[*]NSLog(urlstr);
[*]NSLog(strcontext);
[*]assert(strcontext != NULL);
[*]assert(urlstr != NULL);
[*]NSData *postData = ;
[*]NSString *postLength = ];
[*]NSMutableURLRequest *request = [[ init] autorelease];
[*]];
[*]; ;//setting timeout
[*];
[*];
[*];
[*]NSURLConnection *conn=[ initWithRequest:requestdelegate:self];
[*]if (conn)
[*]{
[*]NSLog(@"Connection success");
[*].networkActivityIndicatorVisible = YES;
[*];
[*]}
[*]else
[*]{
[*]// inform the user that the download could not be made
[*]}
[*]}
[*]#pargma mark
以下为相应的回调函数
[*]// 收到响应时, 会触发
[*]- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
[*]// 注意这里将NSURLResponse对象转换成NSHTTPURLResponse对象才能去
[*]NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
[*]if () {
[*]NSDictionary *dictionary = ;
[*]NSLog();
[*]NSLog(@"%d",);
[*]}
[*]}
[*]//链接错误
[*]- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[*]//;
[*]NSLog(@"%@",);
[*]}
[*]// Called when a chunk of data has been downloaded.
[*]//接收数据 每收到一次数据, 会调用一次
[*]- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[*]// Process the downloaded chunk of data.
[*]NSLog(@"%d", );
[*]//NSLog(@"%@", [ initWithData:data encoding:NSUTF8StringEncoding]);
[*]//;
[*]}
[*]//接收结束
[*]- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[*]NSLog(@"%@",connection);
[*]//NSLog(@"%lld", received_);
[*]//;
[*]// Set the condition which ends the run loop.
[*]}
小结:iPhone应用用HTTP协议和服务器通信的内容介绍完了,希望通过本文的学习能对你有所帮助!
【编辑推荐】
[*]iPhone应用中如何获取硬件版本以及系统信息
[*]详解iPhone应用开发中缓存文件
[*]iPhone应用数据存储Sqlite3第三方框架FMDB
[*]iPhone应用学习笔记之对象初始化
[*]详解iPhone应用自动化测试案例实现
页:
[1]