如何使用Objective-C中的参数向服务发送JSON请求

时间:2012-04-10 11:23:20

标签: objective-c

我正在创建一个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中实现?

2 个答案:

答案 0 :(得分:1)

USE Post method.try this

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

你可以追加这样的所有参数。

答案 1 :(得分:1)

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

另请参阅此问题post-data-through-json-webservices-in-iphone