IOS AFNetWorking 通過body傳遞參數給服務器


https://www.jianshu.com/p/d3d31e55fafa

 

https://blog.csdn.net/ximiaoweilai/article/details/102942632

 

post請求體封裝如下:

- (void)postWithUrl:(NSString *)url body:(NSData *)body  success:(void(^)(NSDictionary *response))success failure:(void(^)(NSError *error))failur

{

NSString *requestUrl = @“”;

AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

//如果你不需要將通過body傳 那就參數放入parameters里面

NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:requestUrl parameters:nil error:nil];

NSLog(@"requestURL:%@",requestUrl);

request.timeoutInterval= 10;

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

// 設置body 在這里將參數放入到body

[request setHTTPBody:body];

AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];

responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",

@"text/html",

@"text/json",

@"text/javascript",

@"text/plain",

nil];

manager.responseSerializer = responseSerializer;

[[manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse *response,id responseObject,NSError *error){

if(responseObject!=nil){

success(responseObject);

}

if (error) {

failure(error);

}

}]resume];

}

 

調用:

NSDictionary *dict = @{@"name":@"hello",@"sex":@"男"};

NSData *data =    [NSJSONSerialization dataWithJSONObject:dict options:NSUTF8StringEncoding error:nil];

[self postWithUrl:@"" body:data showLoading:0 success:^(NSDictionary *response) {

//NSString *result = [[NSString alloc] initWithData:response  encoding:NSUTF8StringEncoding];

NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:nil];  //解析

NSLog(@"%@",result);

} failure:^(NSError *error) {

}];

 

IOS AFN 通過body傳遞參數給服務器

2017-07-10 20:19 行走在砂礫中 

  1. 此段代碼適用於請求接口時傳參為json格式,而非常見的dictionary。同時設置請求頭的Content-Type: application/json;charset=UTF-8
  2. 先將AFN文件導入 或者pod 。

AFNetwoking的默認Content-Type是application/x-www-form-urlencodem。若服務器要求Content-Type為applicaiton/json,為了和服務器對應,就必須修改AFNetworking的Content-Type

===========剛在其他博主里看到更省事的代碼,下面的這段代碼不推薦。可以直接略過用第二段代碼塊===

  1.  
    NSDictionary *parameters= @{@"client_type":@"你的參數",@"你的參數":@"1"};
  2.  
     
  3.  
    //設置參數 根據你們服務器的格式設置。我們的后台需要傳的是json格式的
  4.  
     
  5.  
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters 
  6.  
    options: NSJSONWritingPrettyPrinte  error:nil];
  7.  
     
  8.  
      //afn請求
  9.  
     AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:
  10.  
    [ NSURLSessionConfiguration defaultSessionConfiguration]];
  11.  
     
  12.  
          NSString * requestUrl  = @"你的請求地址";
  13.  
        //如果你不需要在請求體里傳參 那就參數放入parameters里面
  14.  
           NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer]
  15.  
    requestWithMethod: @"POST" URLString:requestUrl parameters:nil error:nil];
  16.  
     
  17.  
    // NSLog(@"requestURL:%@",requestUrl);
  18.  
    request.timeoutInterval= 10;
  19.  
     
  20.  
    //這句話很重要,設置"Content-Type"類型 json類型跟后台大哥的一致
  21.  
    [request setValue: @"application/json" forHTTPHeaderField:@"Content-Type"];
  22.  
        // 設置參數放入到body請求體里。后台大哥讓參數放在請求體里,因為沒寫這句代碼,我TM調試浪費了半天
  23.  
        [request setHTTPBody:jsonData];
  24.  
     
  25.  
        AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];
  26.  
        responseSerializer.acceptableContentTypes = [ NSSet setWithObjects:@"application/json",
  27.  
    @"text/html","text/json", @"text/javascript",@"text/plain",  nil];
  28.  
     
  29.  
            manager.responseSerializer = responseSerializer;
  30.  
     
  31.  
        [[manager dataTaskWithRequest:request uploadProgress: nil downloadProgress:nil
  32.  
    completionHandler:^( NSURLResponse *response,id responseObject,NSError *error){
  33.  
     
  34.  
               if(responseObject!=nil){
  35.  
     
  36.  
                   NSString *result = [[NSString alloc] initWithData:responseObject 
  37.  
    encoding: NSUTF8StringEncoding];
  38.  
      NSLog(@"%@",result);
  39.  
     
  40.  
               }
  41.  
     
  42.  
           }]resume];

    第二種解決方法:推薦

  1.  
     
  2.  
    NSDictionary *parameters= @{@"client_type":@"你的參數",@"你的參數":@"1"};
  3.  
     
  4.  
     
  5.  
     
  6.  
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
  7.  
    session.responseSerializer.acceptableContentTypes = [ NSSet setWithObjects:@"application/json", @"text/html", @"text/plain", nil];
  8.  
    //post 發送json格式數據的時候加上這兩句。
  9.  
    session.requestSerializer = [AFJSONRequestSerializer serializer];
  10.  
    session.responseSerializer = [AFJSONResponseSerializer serializer];
  11.  
    session.requestSerializer.timeoutInterval = 15;
  12.  
    // NSString * requestUrl = @"http://47.244.143.48:8080/auth/getVerificationCode";
  13.  
    NSString * requestUrl = @"http://192.168.1.10:8080/auth/getVerificationCode";
  14.  
    [session POST:requestUrl parameters:parameters progress:^( NSProgress * _Nonnull uploadProgress) {
  15.  
     
  16.  
    } success:^( NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  17.  
    if (responseObject) {
  18.  
    NSLog(@"post成功了%@",responseObject);
  19.  
    }
  20.  
     
  21.  
    } failure:^( NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  22.  
    if (error) {
  23.  
    NSLog(@"post失敗了%@",error);
  24.  
    }
  25.  
    }];


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM