afnetworking 3.0 迁移:如何使用标头和 HTTP 正文进行 POST [英] afnetworking 3.0 Migration: how to POST with headers and HTTP Body
问题描述
我正在尝试向 youtube API 发出具有 HTTPHeader 字段和 HTTP 正文的 POST 请求.
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
但是我似乎找不到 AFHTTPSessionManager
的 HTTPRequestOperationWithRequest
方法.
The migration docs for version 3.0 replaces AFHTTPRequestOperationManager
with AFHTTPSessionManager
However I can't seem to find a HTTPRequestOperationWithRequest
method for the AFHTTPSessionManager
.
我尝试使用 constructingBodyWithBlock
但它不起作用可能是因为我没有正确使用它.
I tried using the constructingBodyWithBlock
but it doesn't work maybe because I am not doing it correctly.
这是我目前所没有的:
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
.确保在为 content-type 设置 Header 字段后设置正文,否则 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.
然后在管理器上使用上述 NSMutableURLRequest
创建一个 dataTaskWithRequest
.不要忘记在最后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屋!