NSURLConnection iOS2.0蘋果原生請求

來源:互聯網
上載者:User

標籤:

get請求1: NSURL*url = [NSURLURLWithString:@"http://127.0.0.1/demo.json"];   
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:1 timeoutInterval:15];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        //
        if (!connectionError) {
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
          

            //判斷伺服器返回是否成功
            if (httpResponse.statusCode == 200) {
                //處理伺服器返回的資料(解析json)
               
                //把json形式的字串 解析成對象
               
//                NSJSONReadingMutableContainers = (1UL << 0),  //返回的數組或字典是可變的
//                NSJSONReadingMutableLeaves = (1UL << 1),  //設定json中的字串是可變的 .但是ios7之後.就不起作用了
               
                //以上兩種方式要求.返回的資料必須是json形式的字串,否則解析會出錯
//                NSJSONReadingAllowFragments = (1UL << 2)  //不要求資料是json形式的字串
               
               
                // 解析json返回的對象,只有兩種類型 字典  數組
                NSError *error= nil;
                id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
                //判斷解析json的時候是否出錯
                if (!error) {
                   
                    NSLog(@"%@",json);
//                    NSLog(@"%@  %@",json[@"message"],[json[@"message"] class]);
                }else{
                    NSLog(@"解析json出錯:%@",error);
                }
            }else{
                NSLog(@"伺服器內部錯誤");
            }
        }else{
            NSLog(@"發送請求錯誤 %@",connectionError);
        }
    }];} get請求2:(要求標頭攜帶參數需要轉義)  @interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
   
   
    //當url的字串,有特殊內容(漢字,空格,url中的特殊符號)    NSString *name = @"abc&123";    //只會對漢字 空格進行百分比符號的轉義    name = [name stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //對url中的特殊符號進行轉義
    name = [self encodeToPercentEscapeString:name];
   
    NSString *pwd = @"abc";
    NSString *str = [NSString stringWithFormat:@"http://127.0.0.1/php/login.php?username=%@&password=%@",name,pwd];
   
    NSURL *url = [NSURL URLWithString:str];
    NSLog(@"%@",url);
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
   
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        //
        if (!connectionError) {
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
            if (httpResponse.statusCode == 200) {
                //
                id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
                NSLog(@"%@",json);
            }else{
                NSLog(@"伺服器內部錯誤");
            }
        }else{
            NSLog(@"請求錯誤%@",connectionError);
        }
    }];
}

//進行url編碼 (但是不對漢字和空格進行編碼)
- (NSString *)encodeToPercentEscapeString: (NSString *) input
{
    NSString *outputStr = (NSString *) CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)input,NULL,(CFStringRef)@"!*‘();:@&=+ $,/?%#[]",kCFStringEncodingUTF8));
    return outputStr;
}

//url解碼
- (NSString *)decodeFromPercentEscapeString: (NSString *) input
{
    return [input
            stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding] ;} post請求:(攜帶參數請求體傳遞) #import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //當url的字串,有特殊內容(漢字,空格,url中的特殊符號)
  
   
    NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/php/login.php"];
 
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //設定發送post請求
    request.HTTPMethod = @"post";
   
    //請求體    沒有對url中的特殊符號轉義
    NSString *name = @"abc123"; //自動對漢字和空格做了百分比符號轉義
   
    NSString *pwd = @"abc";
    NSString *strBody = [NSString stringWithFormat:@"username=%@&password=%@",name,pwd];
    request.HTTPBody = [strBody dataUsingEncoding:NSUTF8StringEncoding];
   
   
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        //
        if (!connectionError) {
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
            if (httpResponse.statusCode == 200) {
                //
                id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
                NSLog(@"%@",json);
            }else{
                NSLog(@"伺服器內部錯誤");
            }
        }else{
            NSLog(@"請求錯誤%@",connectionError);
        }
    }];}

NSURLConnection iOS2.0蘋果原生請求

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.