【问题标题】:How to set the format of JSON post method in iphone如何在iphone中设置JSON post方法的格式
【发布时间】:2011-07-22 10:18:32
【问题描述】:

我正在通过网络服务发送一个帖子请求,但我没有得到我想要的响应。

这是我的代码:

NSString *newurlString = [NSString stringWithFormat:@"{\"name\":\"asit\",\"email\":\"m.kulkarni@easternenterprise.com\",\"businessType\":\"1\",\"score\":30}"];
NSString * url = @"http://www.nieuwe-dag.nl/mobile_be/public/?action=saveScore";
//NSString *urlString =[NSString stringWithFormat:@"name=%@&email=%@&businessType=%d&score=%d",name, email, bussinesstype, score];

NSData *postData = [newurlString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSLog(@"urlString::%@",newurlString);
NSLog(@"postLength::%@",postLength);

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:300];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

NSURLConnection *theConnection =[[NSURLConnection alloc] initWithRequest:request delegate:self];

if (theConnection){
    webData = [[NSMutableData data] retain];
}
else {
    NSLog(@"theConnection is NULL");
}

【问题讨论】:

    标签: iphone objective-c ios json


    【解决方案1】:

    您正在将请求类型设置为 json,但您没有创建 json。您正在创建的数据只是 nsstring。我认为您需要创建一个 json 对象。您可以从这里下载 JSON API:

    https://github.com/stig/json-framework/

    使用 [SBJSONWriter dataWithObject:] 创建 JSON 对象。然后将其传递给您的请求。

    有关 JSON 的更多信息:

    http://www.json.org/

    【讨论】:

      【解决方案2】:

      你需要合适的postData

      NSDictionary *dataDict = @{
          @"name": @"asit", 
          @"email": @"m.kulkarni@easternenterprise.com",
          @"businessType": @"1",
          @"score": @(30)
      };
      
      NSData *postData = [NSJSONSerialization dataWithJSONObject:dataDict options:0 error:nil];
      

      【讨论】:

        猜你喜欢
        • 2020-08-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-12
        相关资源
        最近更新 更多