使用“正文请求”发送NSMutableURLRequest请求

时间:2014-05-18 14:21:35

标签: ios objective-c youtube-api

我目前正在使用YouTube API并允许用户订阅其他频道,但是现在我应该发送包含“请求正文”的POST方法。

这是我应该发送的请求:

POST https://www.googleapis.com/youtube/v3/subscriptions?part=snippet&key={YOUR_API_KEY}


//The Request Body

{
 "snippet": {
  "resourceId": {
   "channelId": "UCJZ7f6NQzGKZnFXzFW9y9UQ"
  }
 }
}

这是我当前的代码

+(void)subscribeToChannel:(NSString *)channelID {
    GTMOAuth2Authentication *auth;
    auth = [GTMOAuth2ViewControllerTouch authForGoogleFromKeychainForName:kKeychainItemName clientID:clientIDclientSecret:clientSecret];


    NSString *urlStr;
    NSMutableURLRequest *request;        
    urlStr = [NSString stringWithFormat:@"https://www.googleapis.com/youtube/v3/subscriptions?id=%@&key=mykey", channelID];

    [request setHTTPBody:[@"{ \"snippet\": { \"resourceId\": { \"channelId\": \"UCJZ7f6NQzGKZnFXzFW9y9UQ\" } } }" dataUsingEncoding:NSUTF8StringEncoding]];

    NSURL *url = [NSURL URLWithString:urlStr];
    request = [NSMutableURLRequest requestWithURL:url];

    [request setHTTPMethod:@"POST"];


    [auth authorizeRequest:request
         completionHandler:^(NSError *error) {

             dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,
                                                      (unsigned long)NULL), ^(void) {


                 NSString *output = nil;
                 if (error) {
                     output = [error description];
                     NSLog(@"ERRO LOADING INFO : %@", output);
                 } else {
                     NSURLResponse *response = nil;
                     NSData *data = [NSURLConnection sendSynchronousRequest:request
                                                          returningResponse:&response
                                                                      error:nil];

                     if (data) {
                         output = [[NSString alloc] initWithData:data
                                                        encoding:NSUTF8StringEncoding];

                     } else {
                         output = [error description];
                     }
                 }



             });
         }];
}

我很肯定我在 [request setHTTPBody] 中做错了什么,但这是我唯一能想到的。

2 个答案:

答案 0 :(得分:5)

您在分配NSMutableURLRequest的实例之前尝试设置NSMutableURLRequest的HTTPBody。

    NSString *urlStr;
    // The request is nil
    NSMutableURLRequest *request;        
    urlStr = [NSString stringWithFormat:@"https://www.googleapis.com/youtube/v3/subscriptions?id=%@&key=mykey", channelID];

    // At this point the request is still nil so you are attempting to set the HTTPBody on a nil object
    [request setHTTPBody:[@"{ \"snippet\": { \"resourceId\": { \"channelId\": \"UCJZ7f6NQzGKZnFXzFW9y9UQ\" } } }" dataUsingEncoding:NSUTF8StringEncoding]]

您还在评论中提到您收到“此API不支持解析表单编码输入”。错误。您可能会收到此错误,因为您没有设置内容类型(我通过Google搜索错误来得出这个结论。我可能错了。)

这应该有效:

    NSString * urlStr = [NSString stringWithFormat:@"https://www.googleapis.com/youtube/v3/subscriptions?id=%@&key=mykey", channelID];

    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];

    [request setHTTPMethod:@"POST"];

    // Set the content type
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

    // Create the dictionary that you will be using in the HTTPBody
    NSDictionary * httpBody = @{
                              @"snippet": @{
                                    @"resourceId": @{
                                            @"channelId": channelID
                                            }
                                    }
                              };

    // Make sure that the above dictionary can be converted to JSON data
    if([NSJSONSerialization isValidJSONObject:httpBody])
    {
        // Convert the JSON object to NSData
        NSData * httpBodyData = [NSJSONSerialization dataWithJSONObject:httpBody options:0 error:nil];
        // set the http body
        [request setHTTPBody:httpBodyData]; 
    }

我在使用Google Places API碰撞地点时执行此操作,但它的工作原理相同。

答案 1 :(得分:0)

试试这个: -

NSMutableDictionary *channelId = [[NSMutableDictionary alloc]init];
[channelId setObject:@"UCJZ7f6NQzGKZnFXzFW9y9UQ" forKey:@"channelId"];
NSMutableDictionary *resourceId = [[NSMutableDictionary alloc]init];
[resourceId setObject:channelId forKey:@"resourceId"];

NSDictionary * postDictionary = [NSDictionary dictionaryWithObject:resourceId forKey:@"snippet"];

NSError * error = nil;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:postDictionary options:NSJSONWritingPrettyPrinted error:&error];
[request setHTTPBody:jsonData];