今天后台让我们提交数据的时候不要提交字典,要提交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];
}