iOS中的请求(GET请求,POST请求,同步请求,异步请求)

1.用到的一些第三方

PostTableViewController.m
#import "PostTableViewController.h"

@interface PostTableViewController ()

@property(nonatomic,retain) NSArray *dataArr;

@end

@implementation PostTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)handleBtnT:(id)sender {
    //1.创建网址字符串对象
    NSString *str = [NSString stringWithFormat:@"http://api.tudou.com/v3/gw"];
    //2.创建NSURL对象
    NSURL *url = [NSURL URLWithString:str];
    //3.创建请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //3.1创建参数字符串
    NSString *parmStr = [NSString stringWithFormat:@"method=album.channel.get&appKey=myKey&format=json&channel=t&pageNo=1&pageSize=10"];
    //3.2设置请求体(提交的内容)
    NSData *data = [parmStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    //3.3设置请求方式
    [request setHTTPMethod:@"POST"];
    
    //4.创建连接
    //同步
    NSData *dataNS = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    
    [self parsingJSON:dataNS];
    
}
//解析

- (void)parsingJSON:(NSData *)data{
    
    NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
   // self.dataArr = dic[@"results"];
    NSLog(@"%@",dic);
    
//    self.descStr.text = dataArr[0][@"dic"];
//    self.actionStr.text = dataArr[0][@"actionStr"];
//    self.categoriesStr.text = dataArr[0][@"categoriesStr"];
    
   // NSLog(@"%@",dic[@"results"][0][@"dic"]);
    //[self.tableView reloadData];
}

- (IBAction)handleBtnY:(id)sender {
}





#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return 20;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseIdentifier" forIndexPath:indexPath];
    
    
    cell.textLabel.text = self.dataArr[0][@"dic"];
    NSLog(@"%@",self.dataArr[0][@"dic"]);
    return cell;
}


- (void)dealloc
{
    self.dataArr = nil;
    [super dealloc];
}


@end
GetTableViewController.m
#import "GetTableViewController.h"
#import "Business.h"
#import "BusinessCell.h"
@interface GetTableViewController ()<NSURLConnectionDataDelegate>
@property (nonatomic, retain) NSMutableArray *dataSourcse;// 存储所有用户数据

@property (nonatomic, retain) NSMutableData *data; //存储数据
@property (nonatomic, retain) NSURLConnection *connection; //存储连接对象
@end

@implementation GetTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSMutableArray *)dataSourcse{
    if (!_dataSourcse) {
        self.dataSourcse = [NSMutableArray arrayWithCapacity:1];
    }
    return [[_dataSourcse retain] autorelease];
}

//同步
- (IBAction)handleBtnT:(id)sender {
   
    
    //1.创建网址字符串对象
    NSString *urlStr = [NSString stringWithFormat:@"http://api.map.baidu.com/place/v2/search?query=%@&region=%@&output=json&ak=6E823f587c95f0148c19993539b99295",@"大保健",@"郑州"];
    //2.如果字符串中出现中文需要URLEncode
    NSString *newURLStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //3.创建NSURL对象
    NSURL *url = [NSURL URLWithString:newURLStr];
    //4.创建请求对象(NSURLRequest)
    NSURLRequest *reques = [NSURLRequest requestWithURL:url];
    
    //同步请求
    //5.建立连接
    NSURLResponse *response = nil; // 存储服务器响应信息
    NSError *error = nil; // 存储请求失败信息
    NSData *data = [NSURLConnection sendSynchronousRequest:reques returningResponse:&response error:&error];
    //解析
    [self parsingJSON:data];
}
//异步连接
- (IBAction)handleBtnY:(id)sender {
    //1.创建网址字符串对象
    NSString *urlStr = [NSString stringWithFormat:@"http://api.map.baidu.com/place/v2/search?query=%@&region=%@&output=json&ak=6E823f587c95f0148c19993539b99295",@"大保健",@"郑州"];
    //2.如果字符串中出现中文需要URLEncode
    NSString *newURLStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //3.创建NSURL对象
    NSURL *url = [NSURL URLWithString:newURLStr];
    //4.创建请求对象(NSURLRequest)
    NSURLRequest *reques = [NSURLRequest requestWithURL:url];
    
    //异步连接
    //1.Block 方式
/*
    [NSURLConnection sendAsynchronousRequest:reques queue:[NSOperationQueue  mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        //解析
        [self parsingJSON:data];
    }];
*/
    //2.协议和代理
   self.connection = [NSURLConnection connectionWithRequest:reques delegate:self];
    

}
//解析
- (void)parsingJSON:(NSData *)data
{
    //清除数组中之前的数据
    [self.dataSourcse removeAllObjects];
    //6.解析
    //此时使用可变字典来接受 , 一方面,解析之后获得是可变的容器,另一方面,得到的数据的最外层是字典,因此,使用可变字典来接受数据.
    NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    // NSLog(@"%@",dic);
    
    //获取字典中的小数组
    NSArray *dataArr = dic[@"results"];
    NSLog(@"%@",dataArr);
    //将小数组中字典对象转化为 Business 类型的对象
    for (NSDictionary *dic in dataArr) {
        Business *business = [[Business alloc] init];
        [business setValuesForKeysWithDictionary:dic];
        //添加到数组
        [self.dataSourcse addObject:business];
        [business release];
    }
    
    //数据解析完毕,刷新界面
    [self.tableView reloadData];
    
    
}

/**
 *  同步链接,异步链接之间的区别
    1.同步连接由主线程完成网络的请求任务,在数据请求完毕之前,所有的用户交互无处理,会造成程序卡顿,影响用户体验.
    2.异步链接,系统默认开辟子线程完成网络请求的任务,主线程依旧处理用户交互,因此,用户体验较好.操作流畅.以空间换时间.

 */

#pragma mark - NSURLConnectionDataDelegate
//当收到服务器响应时触发
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    //当收到服务器响应时,开辟空间
    self.data = [NSMutableData data];
}
//当收到服务器传输的数据时
//当传输的数据比较大时,服务器并不会径所有的数据全部传输过来,可能每次传输一部分,每一次传输都会触发该方法.
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
   //当收到数据时,拼接数据
    [self.data appendData:data];
}
//当接受服务器传输的数据结束时
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    //解析
    [self parsingJSON:self.data];
}
//当请求失败时
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"失败");
    
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return self.dataSourcse.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BusinessCell *cell = [tableView dequeueReusableCellWithIdentifier:@"resuse" forIndexPath:indexPath];
    //Cell 为自身控件赋值
    cell.business = self.dataSourcse[indexPath.row];
    
    return cell;
}

- (void)viewWillDisappear:(BOOL)animated{
    //当将要离开该界面,去其他界面时,终止连接
    [self.connection cancel]; // 取消网络连接
}

- (void)dealloc{
    self.data = nil;
    self.dataSourcse = nil;
    self.connection = nil;
    [super dealloc];
}
@end
Business.h


#import <Foundation/Foundation.h>

@interface Business : NSObject
@property (nonatomic, copy) NSString *name; //存储商户名字
@property (nonatomic, copy) NSString *address; //存储商户地址
@property (nonatomic, copy) NSString *telephone; // 存储商户电话
@property (nonatomic, copy) NSString *business_id;// 存储商户id
@end


Business.m

#import "Business.h"
@implementation Business
//当使用KVC进行赋值时,如果使用赋值的字典中的键值对不能使用完(business)这个类 属性的个数, 少于 键值对的个数  --- 字典中的某些键值对找不到对应得属性来完成属性,此时需要实现下面的方法来处理匹配不到的情况
- (void)setValue:(id)value forUndefinedKey:(NSString *)key
{
    if ([key isEqualToString:@"uid"]) {
        self.business_id = value;
        NSLog(@"---- %@",self.business_id);
    }
}
- (void)dealloc{
    self.name = nil;
    self.address = nil;
    self.telephone = nil;
    
    [super dealloc];
}
@end
BusinessCell.h


#import <UIKit/UIKit.h>
@class Business;
@interface BusinessCell : UITableViewCell
@property (retain, nonatomic) IBOutlet UILabel *cellName;
@property (retain, nonatomic) IBOutlet UILabel *cellAddress;

@property (retain, nonatomic) IBOutlet UILabel *cellPhone;
@property (nonatomic, retain) Business *business;
@end


BusinessCell.m

#import "BusinessCell.h"
#import "Business.h"
@implementation BusinessCell

- (void)awakeFromNib {
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}
//重写Model -- Business 类的属性setter方法为自身控件进行赋值
- (void)setBusiness:(Business *)business{
    if (_business != business) {
        [_business release];
       _business = [business retain];
        
    }
    //为Cell自身的控件进行赋值
    self.cellName.text = business.name;
    self.cellAddress.text = business.address;
    self.cellPhone.text = business.telephone;
}


- (void)dealloc {
    self.business = nil;
    [_cellName release];
    [_cellAddress release];
    [_cellPhone release];
    [super dealloc];
}
@end
ImageViewController.m



#import "ImageViewController.h" #import "ASProgressPopUpView.h" @interface ImageViewController ()<NSURLConnectionDataDelegate> @property (retain, nonatomic) IBOutlet UILabel *detailLB; @property (retain, nonatomic) IBOutlet UIImageView *imageShow; @property (retain, nonatomic) NSMutableData *data; @property (nonatomic, assign) NSUInteger totalLength; // 存储数据的总长度 @property (nonatomic, retain) ASProgressPopUpView *progressView; // 进度条 @end @implementation ImageViewController - (void)viewDidLoad { [super viewDidLoad]; //进度条创建以及配置 self.progressView = [[ASProgressPopUpView alloc] initWithFrame:CGRectMake(20, 100, 280, 0)]; self.progressView.font = [UIFont fontWithName:@"Futura-CondensedExtraBold" size:16]; // 字体 self.progressView.popUpViewAnimatedColors = @[[UIColor redColor], [UIColor orangeColor], [UIColor greenColor]]; self.progressView.popUpViewCornerRadius = 4.0; [self.progressView showPopUpViewAnimated:YES]; //显示动态框 //添加父视图 [self.view addSubview:self.progressView]; //释放 [self.progressView release]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } //请求图片 - (IBAction)handleRequest:(id)sender { //GET请求,同步连接 //1.创建网址字符串对象 NSString *urlsStr = [NSString stringWithFormat:@"http://image.zcool.com.cn/56/13/1308200901454.jpg"]; //2.如果字符串中出现中文需要URLEncode NSString *urlEncode = [urlsStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; //3.创建NSURL对象 NSURL *urlNS = [NSURL URLWithString:urlEncode]; //4.创建请求对象(NSURLRequest) NSURLRequest *urlRequest = [NSURLRequest requestWithURL:urlNS]; //5.建立连接 /* NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:nil]; //解析 self.imageShow.image = [UIImage imageWithData:data]; */ //异步连接 //1.Bloc方式 // [NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { // self.imageShow.image = [UIImage imageWithData:data]; // }]; //2.协议代理 [NSURLConnection connectionWithRequest:urlRequest delegate:self]; } #pragma mark - NSURLConnectionDataDelegate //接受服务区响应触发 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{ //开辟空间 self.data = [NSMutableData data]; //获取数据的总长度 self.totalLength = (NSUInteger)response.expectedContentLength; } //接受数据拼接数据 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ [self.data appendData:data]; CGFloat rate = self.data.length * 1.0 / self.totalLength; self.detailLB.text = [NSString stringWithFormat:@"进度:%.2f%%",rate * 100]; self.progressView.progress = rate; //self.imageShow.image = [UIImage imageWithData:self.data]; } - (void)connectionDidFinishLoading:(NSURLConnection *)connection{ self.imageShow.image = [UIImage imageWithData:self.data]; } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{ } - (void)parsingJSON:(NSData *)data{ //NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; } - (void)dealloc { self.progressView = nil; [_imageShow release]; [_detailLB release]; self.data = nil; [super dealloc]; } @end
原文地址:https://www.cnblogs.com/wohaoxue/p/4805548.html