如何以NSDictionary为参数命中发布请求 [英] How to hit post request with NSDictionary as parameter

查看:284
本文介绍了如何以NSDictionary为参数命中发布请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试点击发送字典作为参数的帖子类型.以下是我到目前为止尝试过的操作,但是我认为格式发送无法正确生成.请指导,代码如下:

I am trying to hit post type sending dictionary as parameter. Below is what i tried so far, but i think format sending is not generating correctly. Please guide, code is below:

需要作为参数发送的数据获取:

Data fetching which need to send as parameter:

NSArray *routesLegsArray = [[[[[json objectForKey:@"routes"]objectAtIndex:0] objectForKey:@"legs"] objectAtIndex:0] objectForKey:@"steps"];


            NSMutableArray *arrSteps = [[NSMutableArray alloc] init];

            for(int i=0; i<[routesLegsArray count]; i++)
            {
                if ([routesLegsArray count] > 0)
                {
                    NSDictionary *routeDict = [routesLegsArray objectAtIndex:i];
                    NSMutableDictionary *dictSteps = [[NSMutableDictionary alloc] init];
                    [dictSteps setValue:[[routeDict objectForKey:@"polyline"]objectForKey:@"points"] forKey:@"encoded_polyline"];
                    [dictSteps setValue:[[routeDict objectForKey:@"polyline"]objectForKey:@"points"] forKey:@"road_name"];

                    [arrSteps addObject: dictSteps];
                }
            }

                completitionBlock(arrSteps, error);

为获取的数据创建NSDictionary,需要将其作为参数发送:

Creating NSDictionary of fetched data which needs to be send as parameter:

NSDictionary *dictVehicle = [[NSDictionary alloc] initWithObjectsAndKeys:@"2", @"axles", nil];


NSDictionary *_attributes = @{
                              @"departure_time": @"2017-07-28T17:39:43.611Z",
                              @"steps":arrSteps,
                              @"vehicle":dictVehicle

                              };
NSString *_baseURLString=[NSString stringWithFormat:@"%@%@",kTollsURL,kAccessKeyTolls];

API命中:

NSURL * url = [NSURL URLWithString:_baseURLString];
NSURLSessionConfiguration * config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession * session = [NSURLSession sessionWithConfiguration:config];


NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = @"POST";

[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

NSDictionary *dictionary = @{@"user": _attributes};
NSError *error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary
                                               options:kNilOptions error:&error];

if (!error) {

    NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request
                                                               fromData:data completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {

                                                                   // Handle response here
                                                                  // NSLog(@"resp:%@", response);

                                                                   NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
                                                                   NSLog(@"dict:%@", dictionary);
                                                               }];

    [uploadTask resume];
}

_attributes的打印说明:

Printing description of _attributes:

{
"departure_time" = "2017-07-28T17:39:43.611Z";
steps =     (
            {
        "encoded_polyline" = "ytfzDqzksM_AgB";
        "road_name" = "ytfzDqzksM_AgB";
    },
            {
        "encoded_polyline" = "yvfzDy}ksMPMf@a@";
        "road_name" = "yvfzDy}ksMPMf@a@";
    },
            {
        "encoded_polyline" = "_ufzDi_lsM}@mB";
        "road_name" = "_ufzDi_lsM}@mB";
    },
            {
        "encoded_polyline" = "}vfzDwblsMb@a@f@a@";
        "road_name" = "}vfzDwblsMb@a@f@a@";
    },
            {
        "encoded_polyline" = "qtfzD{dlsMoA}B";
        "road_name" = "qtfzD{dlsMoA}B";
    }
);
vehicle =     {
    axles = 2;
};
}

收到错误:

code = 400;
message = "parsing route body from \"\" failed, because invalid character 's' looking for beginning of value";

我没有发现问题所在,请进行指导.

I am not getting what is wrong in it, please guide.

下面是实际发送数据的方式,请查看数据是否与我发送的数据相同.

Below is how data actually need to sent, do look also if it's same or not as i am sending.

{
"departure_time": "2017-07-28T17:39:43.611Z",
"steps": [
{
  "encoded_polyline": "iywaHjemiVCDEFEHMP",
  "road_name": "Lake Washington Blvd E"
},
{
"encoded_polyline":"gzwaHtfmiVCAWLYFUAs@S{@a@e@e@}@kAo@cAWi@g@eBm@gCcA{C]q@u@kAm@_Ag@q@s@gAg@ . aAUcAGgAA_CA_@JyDRiI`Bql@p@kHtB{Rv@oHfAcNvI}eAvOkkBbEwZlAoIp@{Et@cKhAmN",
  "road_name": "WA-520 E"
},
{
  "encoded_polyline": "s|vaHnm`iVXwAh@aFPwBD{@H{ABg@@e@?Q? 
QAWAQ@IBQBIDKHKj@ONKLAN?^AF?",
  "road_name": "84th Ave NE"
}
],
"vehicle": {
"axles": 2
}
}

推荐答案

您是否尝试过将字典转换为数据的其他方法?

Have you tried a different way of the dictionary to data conversion?

let data = NSKeyedArchiver.archivedData(withRootObject: dictionary)

服务器可能由于数据表示不正确而无法理解请求.

Maybe the server cannot understand the request because of bad data representation.

这篇关于如何以NSDictionary为参数命中发布请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆