iOS:如何处理以下参数请求?

时间:2014-10-21 17:11:13

标签: php ios objective-c http put

我想知道如何处理以下参数PUT请求?如何存储参数(假设使用NSDictionary),以便将其发送到运行php的服务器。任何提示或建议表示赞赏。

curl -X PUT -d {"questions":[{"type":"control_head" }]}

P.S。以上是API文件给我的内容。 {"questions":[{"type":"control_head" }]}是我需要使用的参数,万一你没有得到它。

1 个答案:

答案 0 :(得分:0)

如果您自己动手,则需要实例化NSMutableURLRequest对象,按照curl(例如PUT请求,JSON正文等)的建议对其进行修改,以及然后通过NSURLConnectionNSURLSession发起请求。

产生类似的东西:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"PUT";
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
NSDictionary *parameters = @{@"questions":@[@{@"type": @"control_head"}]};
NSError *error;
request.HTTPBody = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:&error];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    if (!data) {
        NSLog(@"sendAsynchronousRequest error: %@", connectionError);
        return;
    }

    // parse the response here; given that the request was JSON, I assume the response is, too:

    NSError *parseError;
    id responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
    if (!responseObject) {
        NSLog(@"parsing response failed: %@", parseError);
        NSLog(@"body of response was: %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
        return;
    }

    // now you can look at `responseObject`
}];

您可以使用AFNetworking这样的库来进一步简化:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
NSDictionary *parameters = @{@"questions":@[@{@"type": @"control_head"}]};
[manager PUT:urlString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

(我还没有检查AFNetworking请求的语法,但它是这样的。)