How to set HTTP request body using AFNetwork's AFHTTPRequestOperationManager?

前端 未结 7 1849
死守一世寂寞
死守一世寂寞 2020-12-13 14:49

I am using AFHTTPRequestOperationManager (2.0 AFNetworking library) for a REST POST request. But the manager only have the call to set the parameters.

-((         


        
7条回答
  •  攒了一身酷
    2020-12-13 15:45

    I had the same problem and solved it by adding code as shown below:

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

提交回复
热议问题