当请求发布json数据请求URL显示空白字段时,只查看字典键

时间:2014-11-11 12:27:31

标签: ios nsurlconnection

NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData: [@"{\"id\":\"7\",\"user\":\"alok7@gmail.com\",\"name\":\"Ashok\",\"gender\":\"Male\",\"price\":\"898989\",\"place\":\"disa\",\"time\":\"2014-10-22\",\"given_taken\":\"Given By\"}" dataUsingEncoding:NSUTF8StringEncoding]options: NSJSONReadingMutableContainers error: nil];

NSString *jsonRequest = [NSString stringWithFormat:@"%@",dictionary];// jsonDict];

NSLog(@"jsonRequest is %@", jsonRequest);   

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url1];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[jsonRequest dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%ld",(long)[jsonRequest length]] forHTTPHeaderField:@"Content-Length"];
请求链接上的

输出:

  {"id":"261","user":"","given_taken":"","name":"","gender":"","price":"0","place":"","time":""},{"id":"262","user":"","given_taken":"","name":"","gender":"","price":"0","place":"","time":""},{"id":"263","user":"","given_taken":"","name":"","gender":"","price":"0","place":"","time":""}],"success":1}

1 个答案:

答案 0 :(得分:0)

在您创建NSMutableURLRequest的原始问题中,您调用了[[NSURLConnection alloc] initWithRequest],然后继续尝试完成请求的配置。

但是,initWithRequest将启动请求,因此请确保在实例化NSURLConnection之前完成配置。

此外,请勿拨打start,因为系统会自动为您启动连接。如果您使用start NSURLConnection创建了startImmediately,则只需NO,这在此处不合适。


在修订后的问题中,您提供的代码包含:

NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData: [@"{\"id\":\"7\",\"user\":\"alok7@gmail.com\",\"name\":\"Ashok\",\"gender\":\"Male\",\"price\":\"898989\",\"place\":\"disa\",\"time\":\"2014-10-22\",\"given_taken\":\"Given By\"}" dataUsingEncoding:NSUTF8StringEncoding]options: NSJSONReadingMutableContainers error: nil];
NSString *jsonRequest = [NSString stringWithFormat:@"%@",dictionary];

您需要手动构建JSON字符串,将其转换为NSData,然后将其转换为NSDictionary(出于某种原因使用NSJSONReadingMutableContainers选项)。您之后使用stringWithFormat来获取该字典并将其转换为字符串(但不是有效的JSON)并发送该字典。

我建议(a)不要手动创建JSON字符串,因为它充满了简单的排印错误; (b)只需创建NSDictionary,然后直接创建NSData。例如:

NSDictionary *jsonDictionary = @{
    @"id" : @"7",
    @"user" : @"alok7@gmail.com",
    @"name" : @"Ashok",
    @"gender" : @"Male",
    @"price" : @"898989",
    @"place" : @"disa",
    @"time" : @"2014-10-22",
    @"given_taken": @"Given By"
    };

NSError *error;
NSData *data = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:&error];
NSAssert(data, @"dataWithJSONObject failed: %@", error);

request.HTTPBody = data;

顺便说一句,与您的问题无关,但您不必设置Content-Length,因为NSURLConnection会为您做到这一点。