iOS原生網路請求

weixin_34120274發表於2017-05-22

前言:之前公司有個java牛人,和他一起做一個新的專案,結果他的介面協議,和我之前用過的完全不一樣,試了很多種方法,依舊請求不成功,最後通過其他途徑找到了解決方法,這裡就不再嘮叨這坎坷的路了。

先貼上介面協議
req包包含包頭head和包體body
{
“head”:{
“sessionID”:”xxx” //會話id(暫時不用)
},
“body”:{
}
}
body為請求具體引數

resp包包含包頭head和包體body
{
    “head”:{
        “rct”:0,                //返回錯誤程式碼 0表示正常,其他值為錯誤
        “msg”:”正常”    //錯誤說明
    },
    body:{
    }
}

body內容為各個包具體返回資訊

body裡面就是與後臺互動的主要內容。

下面是我封裝的網路請求的類,get和post

+(void)GET:(NSString *)URL parameters:(NSDictionary *)dic success:(httpRequestSuccess)success failure:(httpRequestFailed)failure{
    //建立配置資訊
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    //設定請求超時時間:5秒
    configuration.timeoutIntervalForRequest = 10;
    //建立會話
    NSURLSession *session = [NSURLSession sessionWithConfiguration: configuration delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HTTPRootPath,URL]]];
    //設定請求方式:POST
    [request setHTTPMethod:@"GET"];
    [request setValue:@"application/json" forHTTPHeaderField:@"content-Type"];
    [request setValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"Accept"];
    
    //data的字典形式轉化為data
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
    //設定請求體
    [request setHTTPBody:jsonData];
    
    NSURLSessionDataTask * dataTask =[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error == nil) {
            NSDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            success(responseObject);
        }else{
            NSLog(@"%@",error);
            failure(error);
        }
    }];
    [dataTask resume];
}
+(void)POST:(NSString *)URL parameters:(NSDictionary *)dic success:(httpRequestSuccess)success failure:(httpRequestFailed)failure{
    //建立配置資訊
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    //設定請求超時時間:5秒
    configuration.timeoutIntervalForRequest = 10;
    //建立會話
    NSURLSession *session = [NSURLSession sessionWithConfiguration: configuration delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HTTPRootPath,URL]]];
    //設定請求方式:POST
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"content-Type"];
    [request setValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"Accept"];
    
    //data的字典形式轉化為data
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
    //設定請求體
    [request setHTTPBody:jsonData];
    
    NSURLSessionDataTask * dataTask =[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error == nil) {
            NSDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            success(responseObject);
        }else{
            NSLog(@"%@",error);
            failure(error);
        }
    }];
    [dataTask resume];
}

使用的時候

NSDictionary *parm = @{@"head":@{@"sessionID":@""},@"body":@{@"userID":user,@"page":[NSString stringWithFormat:@"%d",IndexPage]}};
        [NativeNetWork POST:@"getFirstPageList" parameters:parm success:^(id responseObject) {
            NSLog(@"%@",responseObject);
            NSDictionary * head = [responseObject objectForKey:@"head"];
            NSString *ReturnMessage = [head valueForKey:@"msg"];
            int ReturnCode = [[head valueForKey:@"rtc"] intValue];
            if (ReturnCode == 0) {
                NSDictionary * body = [responseObject objectForKey:@"body"];
                if (IsRefresh) {
                    DataArray = [NSMutableArray arrayWithCapacity:0];
                }
                for (NSDictionary * dic in body) {
                    QuestionModel * model = [[QuestionModel alloc] init];
                    [model setValuesForKeysWithDictionary:dic];
                    [DataArray addObject:model];
                }
                [ListView reloadData];
            }else{
                [self alertViewWithTitle:nil withMessage:ReturnMessage];
            }
        } failure:^(NSError *error) {
            [self alertViewWithTitle:@"獲取列表失敗" withMessage:@"請檢查網路"];
        }];
    });

end

相關文章