How to hit post request with NSDictionary as parameter

橙三吉。 提交于 2019-12-11 18:54:42

问题


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

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 hit:

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

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

Error recieved:

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

回答1:


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.



来源:https://stackoverflow.com/questions/52000079/how-to-hit-post-request-with-nsdictionary-as-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!