iphone和http服务器的通信

iphone和http服务器的通信

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=[strcontextdataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];

[request setURL:[NSURL URLWithString:urlstr]];

[request setHTTPMethod:@"POST"]; [request setTimeoutInterval: 20];//setting timeout

[request setValue:postLength forHTTPHeaderField:@"Content-Length"];

[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

[request setHTTPBody:postData];

NSURLResponse *respone;

NSError *error;

NSData*myReturn=[NSURLConnection sendSynchronousRequest:request returningResponse:&respone

error:error];

NSLog(@"%@", [[NSString alloc] initWithData:myReturn encoding:NSUTF8StringEncoding]);

}

异步方式:一般用于获取大量数据

-(void)UpadaPost:(NSString *)strcontext URL:(NSString *)urlstr{

NSLog(urlstr);

NSLog(strcontext);

assert(strcontext != NULL);

assert(urlstr != NULL);

NSData *postData = [strcontext dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];

[request setURL:[NSURL URLWithString:urlstr]];

[request setHTTPMethod:@"POST"]; [request setTimeoutInterval: 20];//setting timeout

[request setValue:postLength forHTTPHeaderField:@"Content-Length"];

[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

[request setHTTPBody:postData];

NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self];

if (conn)

{

NSLog(@"Connection success");

[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

[conn retain];

}

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 ([response respondsToSelector:@selector(allHeaderFields)]) {

NSDictionary *dictionary = [httpResponse allHeaderFields];

NSLog([dictionary description]);

NSLog(@"%d",[response statusCode]);

}

}

//链接错误

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {

//[self performSelectorOnMainThread:@selector(httpConnectEnd) withObject:nil waitUntilDone:NO];

NSLog(@"%@",[error localizedDescription]);

}

// Called when a chunk of data has been downloaded.

//接收数据 每收到一次数据, 会调用一次

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

// Process the downloaded chunk of data.

NSLog(@"%d", [data length]);

//NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);

//[self performSelectorOnMainThread:@selector(updateProgress) withObject:nil waitUntilDone:NO];

}

//接收结束

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

NSLog(@"%@",connection);

//NSLog(@"%lld", received_);

//[self performSelectorOnMainThread:@selector(httpConnectEnd) withObject:nil waitUntilDone:NO];

// Set the condition which ends the run loop.

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值