1. 程式人生 > >IOS GET POST 同步 非同步請求

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