天天看點

iOS網絡請求總結、GET、POST、同步、異步代碼塊、異步代理、第三方AFNetWorking2.0使用

iOS網絡請求總結、GET、POST、同步、異步代碼塊、異步代理、第三方AFNetWorking2.0使用

首先需要明白,

GET跟POST 差別:

GET請求 ,将參數直接寫在通路路徑上。操作簡單,不過容易被外界看到,安全性不高,位址最多255位元組; POST請求,将參數放到body裡面。POST請求操作相對複雜,需要将參數和位址分開,不過安全性高,參數放在body裡面,不易被捕獲

同步 跟 異步差別:

同步請求可以從網際網路請求資料,一旦發送同步請求,程式将停止使用者互動,直至伺服器傳回資料完成,才可以進行下一步操作,

異步請求不會阻塞主線程,而會建立一個新的線程來操作,使用者發出異步請求後,依然可以對UI進行操作,程式可以繼續運作

以下分别介紹幾種方式的使用:

1.GET 同步請求

    //建立請求路徑

    NSString *strURL = [NSStringstringWithFormat:@"http://192.168.10.252/upload/mapi/index.php?act=register&r_type=1&email=%@&password=%@&user_name=%@",@"[email protected]",@"123456",@"zhangsan"];

    //通過url建立網絡請求

    NSURLRequest *request = [NSURLRequestrequestWithURL:[NSURLURLWithString:strURL]];

    NSError *error =nil;

    //同步方式連接配接伺服器

    NSData *data = [NSURLConnectionsendSynchronousRequest:request returningResponse:nilerror:&error];

    //json 解析傳回資料

    NSDictionary *dic = [NSJSONSerializationJSONObjectWithData:data options:kNilOptionserror:nil];

    NSLog(@"%@",[dicobjectForKey:@"info"]);

2.post 同步請求

    //通過url建立網絡請求

    NSString *strURL = [NSStringstringWithFormat:@"http://192.168.10.252/upload/mapi/index.php?"];

    //通過url建立網絡請求

    NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:[NSURLURLWithString:strURL]];

    //設定請求方式也POST(預設是GET)

    [request setHTTPMethod:@"POST"];

    //設定請求參數

    NSString *body = [NSStringstringWithFormat:@"act=%@&r_type=%d&email=%@&password=%@&user_name=%@",@"register",1,@"[email protected]",@"123456",@"lisi"];

    //需要NSUTF8StringEncoding轉碼

    [request setHTTPBody:[bodydataUsingEncoding:NSUTF8StringEncoding]];

    //同步方式連接配接伺服器

    NSData *data = [NSURLConnectionsendSynchronousRequest:request returningResponse:nilerror:nil];

    //json 解析傳回資料

    NSDictionary *dic = [NSJSONSerializationJSONObjectWithData:data options:kNilOptionserror:nil];

     NSLog(@"%@",[dicobjectForKey:@"info"]);

3.GET 異步代碼塊請求

    NSString *strURL = [NSString stringWithFormat:@"http://192.168.10.252/upload/mapi/index.php?act=register&r_type=1&email=%@&password=%@&user_name=%@",@"[email protected]",@"123456",@"zhangsan"];

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:strURL]];

    NSError *error = nil;

    NSLog(@"111==%@",[NSThread currentThread]);

    //建立異步代碼方式

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

        NSLog(@"222==%@",[NSThread currentThread]);

        //網絡請求結束

        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

        NSLog(@"%@",[dic objectForKey:@"info"]);

        //回到主線程,去重新整理界面

//        self performSelectorOnMainThread:<#(SEL)#> withObject:<#(id)#> waitUntilDone:<#(BOOL)#>

        dispatch_async(dispatch_get_main_queue(), ^{

            //回主線程要做的事情

        });

    }];

4.POST 異步代碼塊請求

    NSString *strURL = [NSStringstringWithFormat:@"http://192.168.10.252/upload/mapi/index.php?"];

    NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:[NSURLURLWithString:strURL]];

    [request setHTTPMethod:@"POST"];

    [request setTimeoutInterval:10];

    NSString *body = [NSStringstringWithFormat:@"act=%@&r_type=%d&email=%@&password=%@&user_name=%@",@"register",1,@"[email protected]",@"123456",@"lisi"];

    [request setHTTPBody:[bodydataUsingEncoding:NSUTF8StringEncoding]];

    [NSURLConnectionsendAsynchronousRequest:request queue:[NSOperationQueuemainQueue] completionHandler:^(NSURLResponse *response,NSData *data, NSError *connectionError) {

        NSDictionary *dic = [NSJSONSerializationJSONObjectWithData:data options:kNilOptionserror:nil];

        NSLog(@"%@",[dicobjectForKey:@"info"]);

    }];

5. 異步代理請求

用代理需要導入協定:NSURLConnectionDataDelegate

@interface ViewController ()<NSURLConnectionDataDelegate>

    NSString *strURL = [NSString stringWithFormat:@"http://192.168.10.252/upload/mapi/index.php?"];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strURL]];

    [request setHTTPMethod:@"POST"];

    NSString *body = [NSString stringWithFormat:@"act=%@&r_type=%d&email=%@&password=%@&user_name=%@",@"register",1,@"[email protected]",@"123456",@"lisi"];

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

    //使用代理的方式做網絡請求

    [NSURLConnection connectionWithRequest:request delegate:self];

#pragma mark -- 網絡請求代理方法實作

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;

{

    NSLog(@"網絡請求總資料量,這個隻執行一次");

    infoData = [[NSMutableData alloc]init];

}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{

    NSLog(@"這個方法會執行多次!");

    [infoData appendData:data];

}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection

{

    NSLog(@"網絡請求結束!!!");

    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:infoData options:kNilOptions error:nil];

    NSLog(@"%@",dict);

    NSLog(@"%@",dict[@"info"]);

}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

{

    NSLog(@"網絡請求失敗。失敗原因%@",error);

}

5. 使用第三方做網絡請求,AFNetWorking2.0

頭檔案導入:

#import "AFNetworking.h"

    AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc]init];

    //設定請求逾時

    manager.requestSerializer.timeoutInterval = 10;

//請求參數配置

    NSDictionary *dict = @{@"act":@"register",@"r_type":@1,@"email":@"[email protected]",@"password":@"111111",@"user_name":@"wangwu1"};

//    manager POST:nil parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

//        //傳檔案的時候,會使用到這裡

//    } success:^(AFHTTPRequestOperation *operation, id responseObject) {

//        <#code#>

//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

//        <#code#>

//    }

    [manager POST:@"http://192.168.10.252/upload/mapi/index.php?" parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {

        //網絡請求成功了

        NSLog(@"11====%@",responseObject);

        NSDictionary *dic = responseObject;

        NSLog(@"%@",[dic objectForKey:@"info"]);

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        //網絡請求失敗了。

        NSLog(@"error == %@",error);

    }];

如有錯誤!歡迎指出。。謝謝!

每天進步一點點,做一個快樂的程式猿!!