AFN请求 将数组作为HTTPBody请求头进行POST请求

摄/爨乡的云
需要传输的数据 dictArr
{
    deviceName = "ISMW2";
    fat = "355";
    macNo = "34:15:13:E9:81:16";
    timestamp = 1533190125;
    userId = 3;
    weight = "27.620001";
},
{
    deviceName = "ISMW2"
    fat = "254";
    macNo = "34:15:13:E9:81:16";
    timestamp = 1533190140;
    userId = 3;
    weight = "29.18";
}
1. 转化为json形式
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictArr options:NSJSONWritingPrettyPrinted error:&error];
if (jsonData && [jsonData length] > 0 && nil == error) {
    jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
}

转化结果:

Printing description of jsonString:
[
  {
    "userId" : "3",
    "weight" : "27.620001",
    "deviceName" : "ISMW2",
    "fat" : "0.0",
    "timestamp" : "1533190125",
    "macNo" : "34:15:13:E9:81:16"
  },
  {
    "userId" : "3",
    "weight" : "29.18",
    "deviceName" : "ISMW2",
    "fat" : "0.0",
    "timestamp" : "1533190140",
    "macNo" : "34:15:13:E9:81:16"
  }
]
2. 使用AFN设置请求头进行网络请求
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:nil error:nil];
[req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
// 关键! 转化为NSaData作为HTTPBody
[req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
    
[[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (!error) {
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                if (success) {
                    success(responseObject);
                }
            }
            NSLog(@"Reply JSON: %@", responseObject);
        } else {
            if (failure) {
                failure(error);
            }
            NSLog(@"Error: %@, %@, %@", error, response, responseObject);
        }
        
}] resume];
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容