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

时间:2017-02-15 06:01:35

标签: ios objective-c 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];

3 个答案:

答案 0 :(得分:1)

您可以使用AFnetworking和Af 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];

注意: - 不要忘记输入恢复

谢谢

答案 1 :(得分:0)

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

 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];

答案 2 :(得分:0)

获得数据

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];