Yury Lego
Yury Lego

Reputation: 21

sending json data to server

I'm sending json data to server and get error

json -

error -

code in obj-c

NSString* json = [dict JSONRepresentation];
//NSString *myRequestString = @"param="; // Attention HERE!!!!
//myRequestString = [myRequestString stringByAppendingString:json];
NSURL *url = [NSURL URLWithString:reqUrlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];


NSData *requestData = [NSData dataWithBytes:[json UTF8String] length:[json length]];

[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: requestData];

Upvotes: 0

Views: 460

Answers (2)

danh
danh

Reputation: 62676

Here's how I pass dates to (and, reciprocally, from) a web service...

NSDate *someDate = [NSDate date];

// get the serverDateFormat in an initial transaction with the server
// or, simpler and more brittle, hardcode something like the following ...
NSString *serverDateFormat = @"yyyy-MM-dd'T'HH:mm:ss'Z'";

// prepare a date formatter.  i allocate and hang onto this at init, but
// you can just do this inline to get started...
_dateFormatter = [[NSDateFormatter alloc] init];
[_dateFormatter setDateFormat:serverDateFormat];
[_dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];

// this is in a category method on NSDate called asHttpParam, but the code
// here works fine to get started. the following gets the date ready to pass to server...
NSString *dateParam = [_dateFormatter stringFromDate:someDate];

The SO date solution you referred to has several problems, including ambiguity about the epoch basis for the date, and a hardcoded GMT to local adjustment. By contrast, dateParam is an unambiguous, absolute date no matter the timezone of the client.

Add the dateParam to your request as you already have it, %-encoding, setting content length, etc.

The server side needs to parse the date into a date. In rails, using the format string above, leads to a date parse that looks like this...

the_date_param = DateTime.parse(params[:the_date_param])

Upvotes: 0

InsertWittyName
InsertWittyName

Reputation: 3940

The answer is to not multiply by 1000 when you create the timestamp (as in the link you provided).

1354119549233 is Fri, 03 May 44880 23:13:53 GMT

1354119549 is Wed, 28 Nov 2012 16:19:09 GMT

Upvotes: 1

Related Questions