需要传输的数据 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];
网友评论