ios - 发送带有 "Body Requests"的 NSMutableURLRequest 请求

标签 ios objective-c youtube-api

我目前正在使用 YouTube API 并允许用户订阅其他 channel ,但现在我应该发送一个包含“请求正文”的 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]中做错了什么,但这是我唯一能想到的事情。

最佳答案

您尝试在分配 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 不支持解析表单编码输入”。错误。您可能会收到此错误,因为您没有设置内容类型(我通过谷歌搜索错误得出了这个结论。我可能是错的)。

这应该有效:

    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 查找地点时执行此操作,但其工作原理应该是相同的。

关于ios - 发送带有 "Body Requests"的 NSMutableURLRequest 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23722929/

相关文章:

ios - 切换播放/暂停按钮循环播放

objective-c - + (instancetype) URLWithString 当我尝试输入非拉丁字符时返回 nil

c# - 如何使用 C# 在 WPF 中播放 YouTube 视频

ios - 如何在按下按钮时将值发送到 ViewController

ios - 用苹果登录抛出授权失败: Error Domain=AKAuthenticationError Code=-7026

ios - 带有 cocoapods 的 FlurrySDK

google-api - 在达到 API 配额限制之前 YouTube 视频上传被拒绝

ios - 如何居中 TabBarItem - Swift

iphone - 在 Objective-C 中更新核心数据中所有或部分托管对象的值的最有效方法是什么

javascript - 无法从Adobe Air访问YouTube API(使用JavaScript)