iOS 网络请求数据两种请求方式GET,POST

来源:互联网 发布:.net是编程语言吗 编辑:程序博客网 时间:2024/06/05 16:13

<span style="font-size:18px;"></span>
两种请求方式的比较

相同点:都能给服务器传输数据 

不同点:

1、给服务器传输数据的方式:

GET:通过网址字符串。POST:通过data

2、传输数据的大小:GET:⽹址字符串最多255字节。POST:使用NSData,容量超过1G

3、安全性:GET:所有传输给服务器的数据,显示在网址里,类似于密码的明文输入,直接可见。

POST:数据被转成NSData(二进制数据),类似于密码的密文输⼊入,⽆无法直接读取。 

连接方式

同步:使用一个线程(主线程)完成所有的工作,效率低,当线程正在执行一个任务的时候无法执行另一个任务,所有如果使用同步进行网络数据的请求,那么在该线程进行网络请求时,暂时无法响应用户的点击事件,用户体验极差

异步:再开一个线程(子线程)去完成任务,此时,主线程依然可以监听用户的点击事件,不会造成卡顿,用户体验较好

异步联接有两种实现⽅方式:

设置代理,接收数据实现block 

异步联接有两种实现⽅方式:

设置代理,接收数据实现block 

代码示例:
//GET同步
<span style="font-size:18px;">//1.创建网址字符串    NSString *urlString = @"http://api.map.baidu.com/place/v2/search?query=银行&region=郑州&output=json&ak=6E823f587c95f0148c19993539b99295";    //2.进行转码    NSString *newUrlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];    //3.创建网址对象    NSURL *url = [NSURL URLWithString:newUrlString]; //   NSLog(@"%@", url);    //4.创建网络请求对象    NSURLRequest *request = [NSURLRequest requestWithURL:url];    //5.发起网络请求    NSURLResponse *response = nil;    NSError *error = nil;    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; //   NSLog(@"%@", data);    [self parserJosn:data];</span>
//JSON数据解析
<span style="font-size:18px;">- (void)parserJosn:(NSData *)data{    [self.dataSource removeAllObjects];    NSError *error1 = nil;    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error1];    NSArray *arr = dic[@"results"];    for (NSDictionary *dic in arr) {        Bank *bank = [[Bank alloc] initWithDictionary:dic];        [self.dataSource addObject:bank];        [bank release];    }    [self.tableView reloadData];</span>
<span style="font-size:18px;">}</span>
<span style="font-size:18px;">//GET异步</span>
<span style="font-size:18px;">  // (1)block//    //1.创建网址字符串    NSString *urlString = @"http://api.map.baidu.com/place/v2/search?query=银行&region=郑州&output=json&ak=6E823f587c95f0148c19993539b99295";    //2.转码    NSString *newUrlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];    //3.创建网址对象    NSURL *url = [NSURL URLWithString:newUrlString];//    //4.创建网络请求对象    NSURLRequest *request = [NSURLRequest requestWithURL:url];//    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {//        //解析同上//        [self parserJosn:data];//    }];</span>
<p style="margin-top: 0px; margin-bottom: 0px; font-family: Menlo;"><span style="font-size:18px;"> //(2)delegate</span></p><p style="margin-top: 0px; margin-bottom: 0px; font-family: Menlo;"><span style="font-size:18px;">    [NSURLConnection connectionWithRequest:request delegate:self]; </span></p><p style="margin-top: 0px; margin-bottom: 0px; font-family: Menlo;"><span style="font-size:18px;">}</span></p><div><pre name="code" class="objc"><span style="font-size:18px;">#pragma mark - NSURLConnectionDataDelegate//当已经收到服务器响应时触发- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{    //在该方法里创建用于拼接data的对象    self.data = [NSMutableData dataWithCapacity:1];}//已经收到数据时触发(如果数据量过大,该方法调用多次分批返回数据)- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{    [self.data appendData:data];}//数据已经传输完成时触发- (void)connectionDidFinishLoading:(NSURLConnection *)connection{    //数据传输完成后进行解析    [self parserJosn:self.data];    }#pragma mark - NSURLConnectionDelegate//链接发生错误时触发- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{    }</span>




//POST同步
<span style="font-size:18px;">//1.生成网址字符串    NSString *urlString = @"http://api.tudou.com/v3/gw";    //2.创建网址对象    NSURL *url = [NSURL URLWithString:urlString];    //3.创建请求参数字符串    NSString *parmString = @"method=album.channel.get&appKey=myKey&format=json&channel=t&pageNo=1&pageSize=10";    //4.对参数字符串进行转码    NSString *newParmString = [parmString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];    //5,创建请求对象    NSMutableURLRequest *mutableRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];    //6.设置请求体    [mutableRequest setHTTPBody:[newParmString dataUsingEncoding:NSUTF8StringEncoding]];    //7.设置请求类型    [mutableRequest setHTTPMethod:@"POST"];    //8.发起网络链接请求    NSData *data = [NSURLConnection sendSynchronousRequest:mutableRequest returningResponse:nil error:nil]; //   NSLog(@"%@", data);    [self parserJosn:data];</span>

<span style="font-size:18px;">- (void)parserJosn:(NSData *)data{    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];    NSDictionary *dic1 = dic[@"multiResult"];    NSMutableArray *arr = dic1[@"results"];    NSLog(@"%@", dic1);    for (NSDictionary *dic in arr) {        PostModel *model = [[PostModel alloc] initWithDictionary:dic];        [self.dataSource addObject:model];    }    [self.tableView reloadData];}</span>
//POST异步
<span style="font-size:18px;">//(1)block    NSString *urlString = @"http://api.tudou.com/v3/gw";    NSURL *url = [NSURL URLWithString:urlString];    NSString *parmString = @"method=album.channel.get&appKey=myKey&format=json&channel=t&pageNo=1&pageSize=10";    NSString *newParmString = [parmString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];    [request setHTTPBody:[newParmString dataUsingEncoding:NSUTF8StringEncoding]];    [request setHTTPMethod:@"POST"];//    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {//        [self parserJosn:data];//    }];    //(2)delegate    [NSURLConnection connectionWithRequest:request delegate:self];}#pragma mark - NSURLConnectionDataDelegate- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{    self.data = [NSMutableData dataWithCapacity:1];}- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{    [self.data appendData:data];}- (void)connectionDidFinishLoading:(NSURLConnection *)connection{    [self parserJosn:self.data];}#pragma mark - NSURLConnectionDelegate- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{    }</span>


请求图片并给它加上一个进度条(添加的label)
<span style="font-size:18px;">//1.创建网址字符串    NSString *imageURL = @"http://image.zcool.com.cn/56/13/1308200901454.jpg";    //2.转码    NSString *newImageURl = [imageURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];    //3.生成网址对象    NSURL *url = [NSURL URLWithString:newImageURl];    //4.创建请求对象    NSURLRequest *request = [NSURLRequest requestWithURL:url];    //5.发起网络请求    [NSURLConnection connectionWithRequest:request delegate:self];    #pragma mark - NSURLConnectionDataDelegate- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{    self.data = [NSMutableData data]; //   NSLog(@"%lld", response.expectedContentLength);    //存储文件的总大小    self.length = response.expectedContentLength;}- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{    [self.data appendData:data];    self.image.image = [UIImage imageWithData:self.data];    //把实时计算的结果赋值给label   // self.progressBar.text = [NSString stringWithFormat:@"%ld / %llu", self.data.length,  self.length];    self.progressBar.text = [NSString stringWithFormat:@"%.2f%%", self.data.length * 1.0 / self.length * 100];}- (void)connectionDidFinishLoading:(NSURLConnection *)connection{    }#pragma mark - NSURLConnectionDelegate- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{    }</span>







0 0
原创粉丝点击