ios - 如何使用 AFNetwork 的 AFHTTPRequestOperationManager 设置 HTTP 请求体?

标签 ios iphone objective-c ipad afnetworking

我正在使用 AFHTTPRequestOperationManager(2.0 AFNetworking 库)进行 REST POST 请求。但是管理器只有设置参数的调用。

-((AFHTTPRequestOperation *)POST:(NSString *)URLString
                  parameters:(NSDictionary *)parameters
                     success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                     failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;

我还需要用字符串设置 HTTP 请求正文。我如何使用 AFHTTPRequestOperationManager 来做到这一点?谢谢。

最佳答案

我遇到了同样的问题,通过添加代码解决了这个问题,如下所示:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL
              cachePolicy:NSURLRequestReloadIgnoringCacheData  timeoutInterval:10];

[request setHTTPMethod:@"POST"];
[request setValue:@"Basic: someValue" forHTTPHeaderField:@"Authorization"];
[request setValue: @"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody: [body dataUsingEncoding:NSUTF8StringEncoding]];

AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

    NSLog(@"JSON responseObject: %@ ",responseObject);

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", [error localizedDescription]);

}];
[op start];

关于ios - 如何使用 AFNetwork 的 AFHTTPRequestOperationManager 设置 HTTP 请求体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19712612/

相关文章:

iphone - 验证电话号码

ios - XCode Swift 自动完成在构建后崩溃

ios - 有没有办法让 UIStackView 的 subview 在隐藏时参与自动布局?

iphone - 如何在 MPMovieplayercontroller 中将视频旋转 90º

ios - 如何从类方法设置@IBOutlet 文本

ios - 在警报 Controller 隐藏之前检查文本字段中的值 - iOS swift

iOS( swift ): Core data transformable attributes

iphone - iPhone 应用程序在存储数据时如何交互?

objective-c - 自动@synthesized ivars 如何影响*real* sizeof(MyClass)?

objective-c - 如何在一个实体(控件)中组合多个 iOS 控件?