afnetworking 3.0迁移:如何使用标头和HTTP正文进行POST [英] afnetworking 3.0 Migration: how to POST with headers and HTTP Body

查看:161
本文介绍了afnetworking 3.0迁移:如何使用标头和HTTP正文进行POST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试发出一个POST请求,其中包含HTTPHeader字段和HTTP主体到youtube API。

I am trying to make a POST request which has HTTPHeader Fields and a HTTP body to the youtube API.

以前在AFNetworking的2.0版本中,我曾经这样做过:

Previously in version 2.0 of AFNetworking, I used to do it this way which worked:

NSDictionary *parameters = @{@"snippet": @{@"textOriginal":self.commentToPost.text,@"parentId":self.commentReplyingTo.commentId}};

NSString *url = [NSString stringWithFormat:@"https://www.googleapis.com/youtube/v3/comments?part=snippet&access_token=%@",[[LoginSingleton sharedInstance] getaccesstoken]];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters
   options:0
     error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

// And finally, add it to HTTP body and job done.
[request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];



AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer.timeoutInterval=[[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request progress:nil success:^(NSURLSessionTask *task, id responseObject) {
    NSLog(@"Reply JSON: %@", responseObject);


    }
} failure:^(NSURLSessionTask *operation, NSError *error) {
    NSLog(@"Error: %@, %@, %@, %@, %@", error, operation.responseObject, operation.responseData, operation.responseString, operation.request);

}];
[operation start];

版本3.0的迁移文档替换 AFHTTPRequestOperationManager 使用 AFHTTPSessionManager
但是我似乎无法为 HTTPRequestOperationWithRequest 方法> AFHTTPSessionManager 。

The migration docs for version 3.0 replaces AFHTTPRequestOperationManager with AFHTTPSessionManager However I can't seem to find a HTTPRequestOperationWithRequest method for the AFHTTPSessionManager.

我尝试使用 constructBodyWithBlock 但它不起作用因为我没有正确地做到这一点。

I tried using the constructingBodyWithBlock but it doesn't work maybe because I am not doing it correctly.

这是我到目前为止所做的不起作用:

This is what I have so far which doesn't work:

NSDictionary *body = @{@"snippet": @{@"topLevelComment":@{@"snippet":@{@"textOriginal":self.commentToPost.text}},@"videoId":self.videoIdPostingOn}};

NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body
   options:0
     error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializer];
serializer.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue];
[serializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[serializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];


[manager POST:[NSString stringWithFormat:@"https://www.googleapis.com/youtube/v3/commentThreads?part=snippet&access_token=%@",[[LoginSingleton sharedInstance] getaccesstoken]] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {

    [formData appendPartWithHeaders:nil body:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];

}  progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    NSLog(@"Reply JSON: %@", responseObject);

} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    NSLog(@"Error: %@, %@, %@, %@, %@", error, operation.responseObject, operation.responseData, operation.responseString, operation.request);

}];


推荐答案

我能够自己解决这个问题。

I was able to figure this out myself.

这是解决方案。

首先,您需要从 AFJSONRequestSerializer NSMutableURLRequest >首先,您可以将方法类型设置为POST。

First, you need to create the NSMutableURLRequest from AFJSONRequestSerializer first where you can set the method type to POST.

在此请求中,在设置 HTTPHeaderFields后,您将获得 setHTTPBody 。确保在为内容类型设置标题字段后设置正文,否则api将给出400错误。

On this request, you get to setHTTPBody after you have set your HTTPHeaderFields. Make sure to set the body after you have set the Header fields for content-type, or else the api will give a 400 error.

然后在管理器上创建一个 dataTaskWithRequest 使用上面的 NSMutableURLRequest 。不要忘记 resume 最后的dataTask,否则什么都不会发送。这是我的解决方案代码,希望有人成功使用它:

Then on the manager create a dataTaskWithRequest using the above NSMutableURLRequest. Don't forget to resume the dataTask at the very end or else nothing will get sent yet. Here's my solution code, hopefully someone gets to use this successfully:

NSDictionary *body = @{@"snippet": @{@"topLevelComment":@{@"snippet":@{@"textOriginal":self.commentToPost.text}},@"videoId":self.videoIdPostingOn}};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"https://www.googleapis.com/youtube/v3/commentThreads?part=snippet&access_token=%@",[[LoginSingleton sharedInstance] getaccesstoken]] parameters:nil error:nil];

req.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue];
[req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];


[[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {

    if (!error) {
        NSLog(@"Reply JSON: %@", responseObject);

        if ([responseObject isKindOfClass:[NSDictionary class]]) {
              //blah blah
        }
    } else {
        NSLog(@"Error: %@, %@, %@", error, response, responseObject);
    }
}] resume];

这篇关于afnetworking 3.0迁移:如何使用标头和HTTP正文进行POST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆