我正在使用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": @"[email protected]",
@"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,但是如果我现在运行代码,它将给我错误:400,这意味着如果input_values为空,则会输出错误的请求错误。
最佳答案
@interface AFJSONRequestSerializer:AFHTTPRequestSerializer
使用is a subclass of
的AFJSONRequestSerializer that encodes parameters as JSON
AFHTTPRequestSerializer NSJSONSerialization
。
添加此AFJSONRequestSerializer
用于发送JSON而不是原始数据添加此并尝试一次
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
例如
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": @"[email protected]",
@"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": @"[email protected]",
@"3": @"newworldorder"};
NSMutableDictionary *modify = [NSMutableDictionary new];
[modify setObject:params forKey:@"input_values"];
你得到的输出