如何在 NSJSONSerialization 中添加字典作为 HTTPBody 的请求参数?

How to add Dictionary as a Request Parameter For HTTPBody in NSJSONSerialization?

我在不使用 AFNetworking 框架的情况下创建一个演示 Web 服务代码。 我的 HTTP Request 参数在 Dictionary 中。 如何在 HTTPBody 上设置它?

我的代码如下

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl];

[request setHTTPMethod:@"POST"];

NSString *postString = "Request Parameter";

[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
//  NSLog(@"requestReply: %@", requestReply);

    NSError *jsonError;
    NSData *objectData = [requestReply dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
                                                         options:NSJSONReadingMutableContainers
                                                           error:&jsonError];
    NSLog(@"requestReply: %@", json);

}] resume];

用我的工作代码检查你的情况,

 NSMutableURLRequest *_request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URL]
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:50.0];
[_request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; // Interact your backend developer for header
[_request addValue:@"application/json" forHTTPHeaderField:@"Accept"];// Interact your backend developer for header

[_request setHTTPMethod:@"POST"];

NSError *error;
NSData *_inputData = [NSJSONSerialization dataWithJSONObject:inputDictionary options:0 error:&error];
[_request setHTTPBody:_inputData];

NSURLSessionDataTask *_fetchData = [[[self class] session] dataTaskWithRequest:_request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if(!error) {
        NSError* error;
        completionBlock(data,error,1);
    } else {
        completionBlock(data,error,0);
    }
}];
[_fetchData resume];

获取数据

NSURL *stringwithUrl = [NSURL URLWithString:@"XXXX"];
    NSMutableURLRequest *requestUrl = [NSMutableURLRequest requestWithURL:stringwithUrl];
    [requestUrl setHTTPMethod:@"POST"];

    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"Value==",@"Key", nil];
    NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];

    NSString *mainString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];

    NSString *requestString = @"request=";

    NSString *finalString = [requestString stringByAppendingString:mainString];

    [requestUrl setHTTPBody:[finalString dataUsingEncoding:NSUTF8StringEncoding]];

    NSURLSession *sesion = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

    [[sesion dataTaskWithRequest:requestUrl completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

        NSLog(@"%@",dict);

    }]resume];

使用 AFnetworking 和不使用 Af Networking 都可以做到这一点。

NSString *stringUrl = @"xxx";

    NSURLSessionConfiguration *myConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];

    AFHTTPSessionManager *myManager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:myConfiguration];
    AFHTTPResponseSerializer *mySerilizer = [[AFHTTPResponseSerializer alloc]init];
    [myManager setResponseSerializer:mySerilizer];

    NSDictionary *param = [[NSDictionary alloc]initWithObjectsAndKeys:@"value==",@"Token", nil];

    NSData *data = [NSJSONSerialization dataWithJSONObject:param options:NSJSONWritingPrettyPrinted error:nil];

    NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];

    NSDictionary *requestParameter = [NSDictionary dictionaryWithObject:string forKey:@"request"];

    [manager POST:stringUrl parameters:requestParameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        NSError *error;
        if(!error)
        {

            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:&error];
            NSLog(@"%@",dict);

        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

    }];

没有词典

NSString *urlString = @"xxxx";

    // Do any additional setup after loading the view, typically from a nib.
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:configuration];
    AFHTTPResponseSerializer *serilizer = [[AFHTTPResponseSerializer alloc]init];
    [manager setResponseSerializer:serilizer];

    NSDictionary *dict = [[NSDictionary alloc]initWithObjectsAndKeys:@"value",@"key", nil];
    [manager POST:urlString parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        NSError *error;
        if(!error)
        {
            NSDictionary *finalData = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:&error];
            NSLog(@"Final Data is %@",finalData);

        }

} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

}]; 

没有 AFNetworking

 NSString *MyUrlString = @"xxxx";
    NSURL *url = [NSURL URLWithString:MyUrlString];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSString *postString = @"key=value";
    [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];

    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSError *jsonError;
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data
                                                             options:NSJSONReadingMutableContainers
                                                            error:&jsonError];
        NSLog(@"requestReply: %@", json);

    }] resume];

注意:-不要忘记把简历

谢谢