您的位置:首页 > 移动开发 > IOS开发

IOS与服务器交互POST 和 GET

2015-12-01 16:50 344 查看

背景介绍:
        当开发IOS应用时,IOS端会和服务器进行交互。IOS端会向服务器传送数据,如:登录功能,注册功能,发送用户填写信息到服务器等功能,都会用到POST方法。也会从服务器获取数据,就会用到GET方法。接下来,我来讲述一下IOS端与服务器的交互过程:

       当在某种需求下,我需要向服务器发送数据

NSURL *url = [NSURL URLWithString:@"http://xx/xx?user_id=xx&token=xx"];//设置请求的url
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";//POST请求
request.timeoutInterval = 60;
NSData *data = [NSJSONSerialization dataWithJSONObject:dic_test options:0 error:nil];//将发送数据转化成JSON(NSData类型)
request.HTTPBody = data;
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];//设置发送内容类型为 JSON
NSURLConnection *connect = [NSURLConnection connectionWithRequest:request delegate:self];
[connect start];
[m_respond_data setLength:0];//设置接收POST结果的变量(NSMutableData类型)每次发送前先清空数据

 

           实现NSURLConnectionDelegate的代理方法

// 当服务端提供了有效的数据来创建NSURLResponse对象时,代理会收到connection:didReceiveResponse:消息。
// 这个代理方法会检查NSURLResponse对象并确认数据的content-type,MIME类型,文件 名和其它元数据。
// 需要注意的是,对于单个连接,我们可能会接多次收到connection:didReceiveResponse:消息;这咱情况发生在
// 响应是多重MIME编码的情况下。每次代理接收到connection:didReceiveResponse:时,应该重设进度标识
// 并丢弃之前接收到的数据。
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSHTTPURLResponse *res = (NSHTTPURLResponse *)response;
NSLog(@"%@",[res allHeaderFields]);
}
//接收到服务器传输数据的时候调用,此方法根据数据大小执行若干次,将返回的数据全部接收到一起
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[m_respond_data appendData:data];
}
//数据传完之后调用此方法
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *respond = [NSJSONSerialization JSONObjectWithData:m_respond_data options:NSJSONReadingMutableLeaves error:nil];
//根据数据信息将界面作出相应的处理
if ([[respond objectForKey:@"errcode"] isEqualToNumber:[NSNumber numberWithInt:0]])
{
}
}
//网络请求过程中,出现任何错误(断网,连接超时等)会进入此方法
-(void)connection:(NSURLConnection *)connection
didFailWithError:(NSError *)error
{
NSLog(@"%@",[error localizedDescription]);
}

   

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: