IOS中get同步異步請求與post同步異步請求

jopen 9年前發布 | 5K 次閱讀 Objective-C IOS

 #import "ViewController.h"

@interface ViewController ()

@property(nonatomic,strong)UITextView *textView;

@property(nonatomic,copy)NSString *BASE_URL;

@property(nonatomic,copy)NSString *BASE_URL1_PARAM;

@property(nonatomic,strong)NSMutableData *mutableData;

@end

@implementation ViewController

  • (void)viewDidLoad {

    [super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

}

pragma mark - get同步

  • (IBAction)getSyncButtonAction:(UIButton *)sender

{

NSString * BASE_URL= @"www.baidu.com";

//1.準備URL地址

NSURL *url = [NSURL URLWithString:BASE_URL];



//2.準備請求對象

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];



//2.1設置請求方式

[request setHTTPMethod:@"GET"];



//3.準備返回結果

NSURLResponse *response = nil;

NSError *error = nil;



//4.創建鏈接對象,并發送請求,并獲取結果(需要的數據)

NSData *data =  [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];



//5.打印獲取到的一些信息

NSLog(@"結果類型:%@",response.MIMEType);

NSLog(@"請求的網址:%@",response.URL);

NSLog(@"結果長度:%lld",response.expectedContentLength);

NSLog(@"請求到的結果:%@",data);



//6.解析文件

NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];



//7.顯示在textView里

self.textView.text = [NSString stringWithFormat:@"%@",dict];



}

pragma mark - get異步

  • (IBAction)getAsyncButtonAction:(UIButton *)sender

{

//1.準備url地址

NSURL *url = [NSURL URLWithString:_BASE_URL];

//2.創建請求對象

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

//3.創建鏈接對象,發送請求

[NSURLConnection connectionWithRequest:request delegate:self];



}

pragma mark - POST同步

  • (IBAction)postSyncButtonAction:(UIButton *)sender

{

//1.準備網址

NSURL *url = [NSURL URLWithString:_BASE_URL];



//2.準備請求對象

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];



//2.1設置請求方式

[request setHTTPMethod:@"POST"];



//2.2設置請求參數

warning 設置請求參數,需要的是NSData類型

NSData *param = [_BASE_URL1_PARAM dataUsingEncoding:NSUTF8StringEncoding];

[request setHTTPBody:param];



//3.創建鏈接對象,并發送請求,獲取結果

NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];



//4.解析

NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];



//5.顯示

self.textView.text = [NSString stringWithFormat:@"%@",dict];

}

pragma mark - POST異步

  • (IBAction)postAsyncButtonAction:(UIButton *)sender

{

__block ViewController *weakSelf = self;



//1.準備地址

NSURL *url = [NSURL URLWithString:_BASE_URL];

//2.創建請求對象,并設置請求方法和參數

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

[request setHTTPMethod:@"POST"];

[request setHTTPBody:[_BASE_URL1_PARAM dataUsingEncoding:NSUTF8StringEncoding]];



//3.創建鏈接對象,發送請求,在block內部完成分析

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue new]  completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

    //NSLog(@"%@",data);



    //4.解析

    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];



    //5.回到主線程,進行更新頁面

    dispatch_sync(dispatch_get_main_queue(), ^{

        weakSelf.textView.text = [NSString stringWithFormat:@"%@",dict];

    });



}];







}

pragma mark - 清除

  • (IBAction)clearButtonAction:(UIButton *)sender

{

_textView.text = nil;

}

pragma mark - 實現協議方法

pragma mark 開始接收請求結果

  • (void)connection:(NSURLConnection )connection didReceiveResponse:(NSURLResponse )response

{

//初始化

self.mutableData = [NSMutableData data];

}

pragma mark - 接收數據

  • (void)connection:(NSURLConnection )connection didReceiveData:(NSData )data

{

//拼接接收到的數據

[self.mutableData appendData:data];



}

pragma makr - 接收完畢

  • (void)connectionDidFinishLoading:(NSURLConnection *)connection

{

//解析

NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:_mutableData options:NSJSONReadingAllowFragments error:nil];

_textView.text = [NSString stringWithFormat:@"%@",dict];

}

pragma mark - 接收錯誤

  • (void)connection:(NSURLConnection )connection didFailWithError:(NSError )error

{

}- (void)didReceiveMemoryWarning {

[super didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

@end

</pre>

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!