将json数据发送到服务器

时间:2012-11-28 16:32:29

标签: iphone objective-c ios json wcf

我正在向服务器发送json数据并收到错误

json -

  • {    GETDatetime =“/ Date(1354119549)/”; }

错误 -

  • 服务器遇到处理请求的错误。异常消息是'SqlDateTime溢出。必须在1/1/1753 12:00:00 AM和12/31/9999 11:59:59 PM之间。

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

2 个答案:

答案 0 :(得分:1)

答案是在您创建时间戳时乘以1000(如您提供的链接)。

1354119549233是星期五,05五月44880 23:13:53 GMT

1354119549是星期三,2012年11月28日16:19:09 GMT

答案 1 :(得分:0)

以下是我如何将日期传递给(并且相反地)来自Web服务......

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

您提到的SO日期解决方案存在一些问题,包括关于日期的时代基础的模糊性,以及用于本地调整的硬编码GMT。相比之下,无论客户的时区如何,dateParam都是一个明确的绝对日期。

将dateParam添加到您已有的请求中,%-encoding,设置内容长度等。

服务器端需要将日期解析为日期。在rails中,使用上面的格式字符串,会导致日期解析看起来像这样......

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