"+" replaced by " " in json send to server

50 views Asked by At
   NSString *AuthToken = [[NSUserDefaults standardUserDefaults]
                               stringForKey:@"AuthToken"];


        NSString* json =[NSString stringWithFormat:@"{'DeviceId':'%@','DeviceType':'iOS','UM_Identifier':'%@','AuthToken':'%@','Query':'all'}", deviceId, userEmail,  AuthToken];


        NSString *post =[[NSString alloc] initWithFormat:@"jinpAllCustDetails=%@",json];



         NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:@"http://www.google.com"]];



        NSData *postData = [post dataUsingEncoding:NSUnicodeStringEncoding allowLossyConversion:NO];

        NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        [request setURL:url];
        [request setHTTPMethod:@"POST"];

        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPBody:postData];


        NSOperationQueue *queue = [[NSOperationQueue alloc] init];
        [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)

In above code :

  • Auth token received from last webservice response is saved in NSUserdefaults, then used for next webservice request.

  • So for Eg.

    Send auth token : z71VxyfVlBxvNKJ01m64a4oKV9lWEv+fFhHxi+7zyRw=

    But server would receives it as :z71VxyfVlBxvNKJ01m64a4oKV9lWEv fFhHxi 7zyRw=

    ie All occurrences of "+" are replaced by " ". So server considers it as an invalid auth token and the webservices request returns a result accordingly.

Help me to fix this, thanks in advance

1

There are 1 answers

0
Droppy On

That isn't valid JSON as strings should be surrounded with ". Create an NSDictionary of the values and use NSJSONSerialization to create the JSON string, which you know will be valid:

NSDictionary *values = @[
    @"DeviceId": deviceId,
    @"DeviceType": @"iOS",
    @"UM_Identifier": userEmail,
    @"AuthToken": authToken,
    @"Query": @"all"
];

NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:values
                                                   options:0
                                                     error:&error];
NSAssert(jsonData != nil, @"Failed to create JSON data");
NSString jsonString =  [[NSString alloc] initWithData:jsonData
                                             encoding:NSUTF8StringEncoding];