【iOS-網絡】使用異步的post請求

異步請求有兩種,可參考get請求數據

 // 2.1.設置請求路徑
    NSURL *url = [NSURL URLWithString:@"http://192.168.1.200:8080/MJServer/login"];

    // 2.2.創建請求對象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; // 默認就是GET請求
    request.timeoutInterval = 5; // 設置請求超時
    request.HTTPMethod = @"POST"; // 設置爲POST請求

    // 通過請求頭告訴服務器客戶端的類型
    [request setValue:@"ios" forHTTPHeaderField:@"User-Agent"];

    // 設置請求體
    NSString *param = [NSString stringWithFormat:@"username=%@&pwd=%@", username, pwd];
    request.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding];

    // 2.3.發送請求
    NSOperationQueue *queue = [NSOperationQueue mainQueue];
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {  // 當請求結束的時候調用 (拿到了服務器的數據, 請求失敗)
        // 隱藏HUD (刷新UI界面, 一定要放在主線程, 不能放在子線程)
        [MBProgressHUD hideHUD];

        if (data) { // 請求成功
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            NSString *error = dict[@"error"];
            if (error) { // 登錄失敗
                [MBProgressHUD showError:error];
            } else { // 登錄成功
                NSString *success =  dict[@"success"];
                [MBProgressHUD showSuccess:success];
            }
        } else { // 請求失敗
            [MBProgressHUD showError:@"網絡繁忙, 請稍後再試"];
        }
    }];
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章