iOS網絡請求GET方式與POST方式

pragma mark 總結:常用的請求方式有兩種, 一個是GET, 一個是POST, 他兩本質上沒有任何區別, 只是post在請求的時候需要添加一個body, 同步和異步: 都使用異步的方式進行加載, 加載過程中還可以操作其他的功能, 不會出現卡死的情況, 從同步演化出異步, 請求分爲三步: 1. 創建URL 2. 創建請求request, 3. 建立連接, 完成數據請求, iOS9.0之後, NSURLConnection用的越來越侷限, NSURLSession未來更重要

// 同步get請求
NSString *strURL = @"http://api.map.baidu.com/place/v2/search?query=銀行&region=大連&output=json&ak=6E823f587c95f0148c19993539b99295";

    // 因爲網址裏不允許有漢字, 只能有26個字母的大小寫, 數字, 和一些指定的符號, 比如&, %, / 等, 所有有中文的網址要先把中文變成相對應的數字編碼
    // 時間戳
    NSString *strURLEncode = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    // 1. 創建一個URL
    NSURL *url = [NSURL URLWithString:strURLEncode];
    // 2. 發送一個請求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    // 3. 建立一個連接
    // 閒來無事的時候看看NSURLSession
    // 參數1: 把創建好的請求發送
    // 參數2: 返回的響應信息
    // 參數3: 錯誤信息
    NSURLResponse *response = nil;
    NSError *error = nil;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    // 4. 把data進行json解析
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSLog(@"%@", dic);
    NSLog(@"*******************%@", response);





// post請求需要在請求的過程裏, 添加一個body, 添加之後纔可以獲取數據
     NSString *urlStr = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";
    // 1. 創建一個URL
    NSURL *url = [NSURL URLWithString:urlStr];
    // 2. 創建一個請求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    // 指定請求的方式, 默認是get請求
    [request setHTTPMethod:@"post"];
    // body的字符串
    NSString *bodyStr = @"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213";
    // body的字符串變成NSData
    NSData *dataBody = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    // 把bodydata放到request中
    [request setHTTPBody:dataBody];
    // 3. 建立連接
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    // 4. json 解析
    NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
   //    NSLog(@"%@", dic);
    //NSLog(@"%@", string);
    // 打印summary對應的內容
    NSMutableArray *arr = dic[@"news"];
    for (NSDictionary *dic in arr) {
        NSLog(@"\n");
        NSLog(@"\n");
        NSLog(@"**********************************************%@", dic[@"summary"]);
        NSLog(@"\n");
        NSLog(@"\n");
    }
發佈了28 篇原創文章 · 獲贊 2 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章