AFN請求 將數(shù)組作為HTTPBody請求頭進行POST請求

攝/爨鄉(xiāng)的云
需要傳輸?shù)臄?shù)據(jù) 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. 轉(zhuǎn)化為json形式
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictArr options:NSJSONWritingPrettyPrinted error:&error];
if (jsonData && [jsonData length] > 0 && nil == error) {
    jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
}

轉(zhuǎn)化結(jié)果:

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設(shè)置請求頭進行網(wǎng)絡(luò)請求
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"];
// 關(guān)鍵! 轉(zhuǎn)化為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];
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容