【问题标题】:iPhone:Http POST requestiPhone:Http POST 请求
【发布时间】:2012-02-26 10:12:03
【问题描述】:

我需要从我的 iphone 应用程序向服务器发送一些详细信息。

我的详细信息为separate arrays of ID,name,quantitystrings with name,address,phone & email

我需要把 NSmutable 数组数据改成这种 JSON 格式

      [
            {"id":"139","name":"Samosa","quantity":"332","spice":"hot"},
            {"id":"149","name":"rice","quantity":"4","spice":"mild"},
            .....
      ]

我的一个疑问是
[request setHTTPMethod:@"POST"];
上面一行是否足以设置 POST 请求。

如何将上述详细信息添加到 POST 请求中?

【问题讨论】:

    标签: iphone objective-c ios http-post nsurlrequest


    【解决方案1】:

    使用 JSON 序列化程序。你可以使用SBJSON。使用 SBJSON,代码将是这样的:

    SBJsonWriter *jsonWriter = [[[SBJsonWriter alloc] init] autorelease];
    NSString *jsonParams = [jsonWriter stringWithObject:<your-NSArray>];
    

    将此jsonParams 添加到 POST:

    NSString *postData = [jsonParams stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:postURL];
    [urlRequest setHTTPMethod:@"POST"];
    [urlRequest setHTTPBody:[postData dataUsingEncoding:NSUTF8StringEncoding]];
    

    【讨论】:

      【解决方案2】:

      还不够。您还需要(最少):

      NSString *your_request_string = @"the thing in JSON format";
      NSData *your_data = [your_request_string dataUsingEncoding:NSUTF8StringEncoding];
      [request setHTTPBody:your_data];
      

      【讨论】:

        【解决方案3】:

        使用setHTTPBody: 将发布数据添加到您的 HTTP 请求对象。
        使用NSJSONSerialization 序列化您的数组。

        NSMutableArray *array = getSomeArray();
        NSError *err;
        NSData *json;
        
        json = [NSJSONSerialization dataWithJSONObject:array options:0 error:&err];
        if (err) {
            // handle error
        }
        
        NSURL *url = getSomeURL();
        NSMutableURLRequest *req;
        
        req = [NSMutableURLRequest requestWithURL:url];
        [req setHTTPMethod:@"POST"];
        [req setHTTPBody:json];
        
        // send your request
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-03-11
          • 1970-01-01
          • 2014-07-24
          • 2018-08-03
          • 1970-01-01
          • 2016-05-20
          • 2017-03-22
          • 2019-06-25
          相关资源
          最近更新 更多