当前位置:  开发笔记 > IOS > 正文

afnetworking 3.0迁移:如何使用标头和HTTP正文进行POST

如何解决《afnetworking3.0迁移:如何使用标头和HTTP正文进行POST》经验,为你挑选了6个好方法。

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

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

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的迁移文档替换AFHTTPRequestOperationManagerAFHTTPSessionManager 但是我似乎找不到一个HTTPRequestOperationWithRequest方法AFHTTPSessionManager.

我尝试使用constructingBodyWithBlock但它不起作用可能是因为我没有正确地做到这一点.

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

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  _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);

}];

Bruna Garcia.. 64

使用AFNetworking 3.0调用POST方法的另一种方法是:

AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

[manager POST:url parameters:parametersDictionary progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"success!");
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error: %@", error);
    }];

希望能帮助到你!



1> Bruna Garcia..:

使用AFNetworking 3.0调用POST方法的另一种方法是:

AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

[manager POST:url parameters:parametersDictionary progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"success!");
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error: %@", error);
    }];

希望能帮助到你!


对不起,这不是我想要的.我需要某种方式能够在post请求中发送JSON主体.以前,请求上的HTTPBody是这样的.我想出了上面发布的新方式

2> Pranoy C..:

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

这是解决方案.

首先,您需要先创建NSMutableURLRequestfrom AFJSONRequestSerializer,然后将方法类型设置为POST.

根据这个要求,您可以setHTTPBody在设置好后进入HTTPHeaderFields.确保在为内容类型设置标题字段后设置正文,否则api将给出400错误.

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

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];


最好的答案,它帮助了我很多.谢谢.我正在寻找这一天.

3> 小智..:

适用HTTPBody于JSON

[sessionManager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[sessionManager.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, id parameters, NSError * __autoreleasing * error) {

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:error];
    NSString *argString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return argString;
}];

[sessionManager POST:urlString parameters:parameters progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {

    if (completion) {
        completion(responseObject, nil);
    }

} failure:^(NSURLSessionDataTask *task, NSError *error) {

    if (completion) {
        NSData *errorData = [error.userInfo objectForKey:@"com.alamofire.serialization.response.error.data"];
        NSDictionary *responseErrorObject = [NSJSONSerialization JSONObjectWithData:errorData options:NSJSONReadingAllowFragments error:nil];
        completion(responseErrorObject, error);
    }
}];

适用HTTPBody于自定义String格式

[sessionManager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[sessionManager.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, id parameters, NSError * __autoreleasing * error) {

    NSString *argString = [self dictionaryToString:parameters];
    return argString;
}];

[sessionManager POST:urlString parameters:parameters progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {

    if (completion) {
        completion(responseObject, nil);
    }

} failure:^(NSURLSessionDataTask *task, NSError *error) {

    if (completion) {
        NSData *errorData = [error.userInfo objectForKey:@"com.alamofire.serialization.response.error.data"];
        NSDictionary *responseErrorObject = [NSJSONSerialization JSONObjectWithData:errorData options:NSJSONReadingAllowFragments error:nil];
        completion(responseErrorObject, error);
    }
}];



4> 小智..:
 -(void)postRequest:(NSString *)urlStr parameters:(NSDictionary *)parametersDictionary completionHandler:(void (^)(NSString*, NSDictionary*))completionBlock{
        NSURL *URL = [NSURL URLWithString:urlStr];

        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        [manager POST:URL.absoluteString parameters:parametersDictionary progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
            NSError* error;
            NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseObject
                                                                 options:kNilOptions
                                                                   error:&error];

            completionBlock(@"Success",json);
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            NSLog(@"Error: %@", error);
            completionBlock(@"Error",nil);
        }];
    }

这种方法适用于AFNetworking 3.0.



5> Vvk..:

使用通用的NSObjectClass方法通过AFNetworking 3.0调用Wenservices 这是我的重复答案,但是它更新了AFNetworking 3.0 首先使NSObject类像Webservice.hWebservice.m

Webservice.h

@interface Webservice : NSObject

+  (void)requestPostUrl:(NSString *)strURL parameters:(NSDictionary *)dictParams success:(void (^)(NSDictionary *responce))success failure:(void (^)(NSError *error))failure;

@end

Webservice.m 你的nsobject.m文件看起来像这样.(在.m文件中添加两个函数)

#import "Webservice.h"

#define kDefaultErrorCode 12345

@implementation Webservice

+  (void)requestPostUrl:(NSString *)strURL parameters:(NSDictionary *)dictParams success:(void (^)(NSDictionary *responce))success failure:(void (^)(NSError *error))failure {

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager setResponseSerializer:[AFHTTPResponseSerializer serializer]];

    [manager POST:strURL parameters:dictParams progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if([responseObject isKindOfClass:[NSDictionary class]]) {
            if(success) {
                success(responseObject);
            }
        }
        else {
            NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
            if(success) {
                success(response);
            }
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if(failure) {
            failure(error);
        }

    }];
}

@end

确保你必须用成功消息替换你的字典键来处理响应回调函数

像这样使用从任何viewcontroller.m 和任何方法调用这个常用方法viewControllers.暂时我viewDidLoad用来调用这个WS.

 - (void)viewDidLoad {
        [super viewDidLoad];

        NSDictionary *dictParam = @{@"parameter1":@"value1",@"parameter1":@"value2"};

        [Webservice requestPostUrl:@"add your webservice URL here" parameters:dictParam success:^(NSDictionary *responce) {
            //Success
            NSLog(@"responce:%@",responce);
            //do code here
        } failure:^(NSError *error) {
            //error
        }];
    }

在上面的方法中添加您的参数,值和Web服务URL.你可以轻松使用这个NSObjcet类.有关详细信息,请访问AFNetworking 3.0或AFNetworking 2.0的旧装.



6> nadim..:

#Pranoy C的可接受答案已转换为AFNetworking 3.0

    NSError *writeError = nil;

    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:&writeError];
    NSString* jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringCacheData  timeoutInterval:120];

    [request setHTTPMethod:@"POST"];
    [request setValue: @"application/json; encoding=utf-8" forHTTPHeaderField:@"Content-Type"];
    [request setValue: @"application/json" forHTTPHeaderField:@"Accept"];
    [request setHTTPBody: [jsonString dataUsingEncoding:NSUTF8StringEncoding]];

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

    [[manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil 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);
            NSLog(@"Response: %@",response);
            NSLog(@"Response Object: %@",responseObject);

        }
    }] resume];

推荐阅读
臭小子
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有