IOS GET POST 同步 异步请求

iOS SDK为HTTP请求提供了同步和异步请求这两种不同的API,而且可以使用GET或POST等请求方法。下边主要编写了常用到的GET和POST方法。

同步请求的用户体验不是很好,因此很多情况下我们会采用异步调用。

而异步请求会使用NSURLConnection委托协议NSURLConnectionDataDelegate。在请求的不同阶段,会回调委托对象的不同方法。

iOS 9.0已弃用[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

使用POST请求的关键是使用NSMutableURLRequest类替代NSURLRequest类。

#import "ViewController.h"

@interface ViewController ()<NSURLConnectionDataDelegate>
@property (strong, nonatomic) NSMutableData *data;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

/**
 GET同步请求
 */
- (void)requestGET {
    NSString *strURL = @"https://api.github.com/orgs/octokit/repos";
    NSURL *url = [NSURL URLWithString:strURL];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *str = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableLeaves) error:nil];
    NSLog(@"成功完成数据加载:%@",str);
}

/**
 GET异步请求
 */
- (void)requestAsyGET {
    NSString *strURL = @"https://api.github.com/orgs/octokit/repos";
    NSURL *url = [NSURL URLWithString:strURL];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if (connection) {
        self.data = [NSMutableData new];
    }
}

/**
 POST同步请求
 */
- (void)requestPOST {
    NSURL *url = [NSURL URLWithString: @"https://api.github.com/orgs/octokit/repos"];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 10];
    [request setHTTPMethod: @"POST"];
    NSDictionary *parameters = @{@"msgtype":@"text",@"text":@{@"content":@"hello word"}};
    if (parameters) {
        if (![request valueForHTTPHeaderField:@"Content-Type"]) {
            [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
            
        }
        [request setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:nil]];
    }
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *str = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableLeaves) error:nil];
    NSLog(@"成功完成数据加载:%@",str);
}

/**
 POST异步请求
 */
- (void)requestAsyPOST {
    NSURL *url = [NSURL URLWithString: @"https://api.github.com/orgs/octokit/repos"];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 10];
    [request setHTTPMethod: @"POST"];
    NSString *post = @"text=message";
    NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:postData];
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if (connection) {
        self.data = [NSMutableData new];
    }
}

#pragma mark NSURLConnection
// 请求成功并建立连接后,开始接收数据。如数据量很多,会被调用多次。
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.data appendData:data];
}
// 加载数据出现异常。
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"请求失败:%@",[error localizedDescription]);
}
// 成功完成数据加载。
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSString *str = [NSJSONSerialization JSONObjectWithData:self.data options:(NSJSONReadingMutableLeaves) error:nil];
    NSLog(@"成功完成数据加载:%@",str);
}

@end

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值