如何以NSDictionary为参数命中发布请求

时间:2018-08-24 08:08:52

标签: ios iphone http-post nsjsonserialization nsurlsessionuploadtask

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

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

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,需要将其作为参数发送:

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的打印说明:

{
"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";

我没有发现问题所在,请指导。

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

{
"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
}
}

1 个答案:

答案 0 :(得分:0)

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

let data = NSKeyedArchiver.archivedData(withRootObject: dictionary)

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