afn post请求上传文件_iOS 使用AFN post提交Json数据

今天后台让我们提交数据的时候不要提交字典,要提交Json格式的数据,于是我就把字典转化成Json

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];

NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

发现上传之后后台不能接收,说是少了一个 { }。于是就各种百度,发现原来是我的请求头设置错了,所以找到下面这样一个方法,重心设置请求头,结果上传成功:

- (void)postJsonToServer {

NSDictionary *body = @{@"UI_NAME":@"FSEAFNSEFN"};

NSError *error;

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];

NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

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

NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:@"http://124.128.94.156:8000/api/UserApi/BusinessRegisterPic" parameters:nil error:nil];

req.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue];

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

[req setValue:@"application/json" forHTTPHeaderField:@"Accept"];

[req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];

[[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {

if (!error) {

NSLog(@"Reply JSON: %@", responseObject);

if ([responseObject isKindOfClass:[NSDictionary class]]) {

//blah blah

}

} else {

NSLog(@"Error: %@, %@, %@", error, response, responseObject);

}

}] resume];

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值