0

我正在创建一个 iPhone 应用程序,并试图弄清楚如何创建对包含参数的 web 服务的 JSON 请求。在 Java 中,这看起来像这样

HashMap<String, String> headers = new HashMap<String, String>();

JSONObject json = new JSONObject();

            json.put("nid", null);
            json.put("vocab", null);
            json.put("inturl", testoverview);
            json.put("mail", username); // something@gmail.com
            json.put("md5pw", password); // donkeykong

        headers.put("X-FBR-App", json.toString());

在服务识别请求之前,标头必须包含 JSON 对象和“X-FBR-App”。这将如何在 Objective-C 中实现?

4

2 回答 2

1

使用 Post 方法。试试这个

    NSString *method =  @"addProduct"; 
 NSString *jsonstring=@"http://yourdomain.com/product_review_api/product-review.php?"; 
 NSString *urlString = [NSString stringWithFormat:@"%@",jsonstring];
 NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
 [request setURL:[NSURL URLWithString:urlString]];
 [request setHTTPMethod:@"POST"]; 
  NSMutableData *body = [NSMutableData data];
    // image file
   NSData *imageData = UIImageJPEGRepresentation( labelimage, 0.8);
   NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];

      //  parameter method
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"method\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[method dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

   //  parameter categoryid
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"category_id\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[selectedID dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

[request setHTTPBody:body];

    // now lets make the connection to the web
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

    NSLog(@"%@",returnString);
    NSDictionary *profile = (NSDictionary*)[returnString JSONValue];
    NSLog(@"profile=%@", profile); 

您可以像这样附加所有参数。

于 2012-04-10T11:40:09.403 回答
1

JSON 并未融入 iOS,但如果您查看www.JSON.org,就会有许多提供所需功能的 Objective-C 框架。我对其中任何一个都没有经验,所以我无法提出建议,但这是寻找解决方案的良好开端。

另请查看此 SO 问题post-data-through-json-webservices-in-iphone

于 2012-04-10T12:01:06.423 回答