我正在使用AFNetworking
将数据发布到网络上。我所拥有的信息是URI
baseURL/post_user_info
,他们希望input
为包含每个名称 - 值对的JSON对象。在编写的代码中下面我在字典中设置了名称 - 值对。我的问题是如何使它成为json并将其作为输入值发送?
NSString *string = [NSString stringWithFormat:@"%@?post_user_info",BaseURLString];
NSString *escapedPath = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSDictionary *params = @{@"input_1": @"hello world",
@"input_2": @"my@you.com",
@"input_3": @"newworldorder"};
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:params options:kNilOptions error:nil];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPBody:jsonData];
[manager POST:escapedPath parameters:[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding] progress:nil success:^(NSURLSessionTask *task, id responseObject)
{
NSLog(@"%@",responseObject);
}failure:^(NSURLSessionTask *operation, NSError *error)
{
NSLog(@"%@",[error localizedDescription]);
}];
我已经更新了代码,因为现在我已经生成了JSON,但如果我现在运行代码,它会给我Error:400,这意味着如果input_values为空,将输出错误的请求错误。
答案 0 :(得分:2)
@interface AFJSONRequestSerializer:AFHTTPRequestSerializer
AFJSONRequestSerializer
is a subclass of
AFHTTPRequestSerializerthat encodes parameters as JSON
使用NSJSONSerialization
。
添加此AFJSONRequestSerializer
用于发送JSON而非原始数据添加此项并尝试一次
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
<强> e.g 强>
NSString *string = [NSString stringWithFormat:@"%@?post_user_info",BaseURLString];
NSString *escapedPath = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
/************** karthik Code added ******************/
AFHTTPSessionManager* manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
/************** karthik Code added ******************/
NSDictionary *params = @{@"1": @"hello world",
@"2": @"my@you.com",
@"3": @"newworldorder"};
[manager POST:escapedPath parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject)
{
NSLog(@"%@",responseObject);
NSError *error = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
NSLog(@"json == %@", json);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(@"%@", [error localizedDescription]);
}];
更新参数
NSDictionary *params = @{@"1": @"hello world",
@"2": @"my@you.com",
@"3": @"newworldorder"};
NSMutableDictionary *modify = [NSMutableDictionary new];
[modify setObject:params forKey:@"input_values"];
你得到
的输出