1. 程式人生 > >iOS-95-網路請求方式彙總(包含AFNetworking、NSMutableURLRequest)

iOS-95-網路請求方式彙總(包含AFNetworking、NSMutableURLRequest)

文章包涵AFNetworking、NSMutableURLRequest兩種請求方式:get、post、上傳圖片、解決上傳base64編碼圖片過長問題(使用【2、post  第一種配置】即可解決)

比如報錯:err:Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: too long (414)" 

一、AFNetworking篇

1、get

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//申明返回的結果是json型別
manager.responseSerializer=[AFJSONResponseSerializer serializer];
//申明請求的資料是json型別
manager.requestSerializer=[AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//    [self.HUD showLoading];
//請求時帶請求頭
[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

// 設定header
NSString *header = @"自定義header格式";
[manager.requestSerializer setValue:header forHTTPHeaderField:kHeaderKey];

__weak typeof(self) weakSelf = self;
[manager GET:url parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
    
} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    
    NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
    NSLog(@"+++++%@",result);
    NSDictionary *dic = [weakSelf dictionaryWithJsonString:result];
    
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    
}];

2、post  第一種配置
NSString *url = @"http://···········";
// 特別說明:像base64編碼後的圖片比較大,使用這種方式即可
NSDictionary *paramDic = @{
                           @"base64Str":imageStr,
                           @"number":@"12344",
                           @"name":name,
                           @"key":@"key",
                           };
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
__weak typeof(self)  weakself = self;
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain",@"image/png",nil];
[self.HUD showLoading];
[manager POST:url parameters:paramDic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
    NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
    NSLog(@"+++++%@",result);
    NSDictionary *object = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    NSLog(@"++++++   %@",error);
}];

3、post 第二種配置。  與【2】基本一致
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//申明返回的結果是json型別
manager.responseSerializer=[AFJSONResponseSerializer serializer];
//申明請求的資料是json型別
manager.requestSerializer=[AFJSONRequestSerializer serializer];
//請求時帶請求頭
__weak typeof(self) weakself = self;
[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[manager POST:URL parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    
}];

4、post  上傳圖片
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//申明返回的結果是json型別
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain",@"image/png",nil];
//提交資料及檔案(圖片、其他格式檔案)
[manager POST:kAddFeedbackURL parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    // 在此處新增要傳送的檔案   (原理:block回撥)
    [formData appendPartWithFileData:nil name:nil fileName:nil mimeType:@"application/octet-stream; charset=UTF-8"]; //image/jpeg
    [formData appendPartWithFileData:photoData2 name:@"img2" fileName:fileName2 mimeType:@"image/jpeg"];
}
     progress:^(NSProgress * _Nonnull uploadProgress) {
         // 進度條
          NSLog(@"service progress...");
     }
      success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
          if (responseObject != nil) {
              NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
              
          }
      }
      failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"POST Error: %@", error.description);
      }
 ];


二、原生方法:NSMutableURLRequest、NSURLSessionDataTask

// 1.建立一個網路路徑
NSURL *url = [NSURL URLWithString:@"http://----"];
// 2.建立一個網路請求,分別設定請求方法、請求引數
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
NSString *args = [NSString stringWithFormat:@"memberId=%@&content=%@",PhoneNumber,content];
request.HTTPBody = [args dataUsingEncoding:NSUTF8StringEncoding];

// 設定header
NSString *header = @"自定義header格式";
[request setValue:header forHTTPHeaderField:kHeaderKey];

// 3.獲得會話物件
NSURLSession *session = [NSURLSession sharedSession];
// 4.根據會話物件,建立一個Task任務
__weak typeof(self) weakSelf = self;
[self.HUD showLoading];
NSURLSessionDataTask *sessionDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    
    NSLog(@"從伺服器獲取到資料");
    /*
     對從伺服器獲取到的資料data進行相應的處理.
     */
    //        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableLeaves) error:nil];
    NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"+++++%@",result);
    NSDictionary *dic = [weakSelf dictionaryWithJsonString:result];
    
    [self performSelectorOnMainThread:@selector(handleResponeDetailInfo:) withObject:dic waitUntilDone:NO];
}];

//5.最後一步,執行任務,(resume也是繼續執行)。
[sessionDataTask resume];