is there an example of AFHTTPClient posting json with AFNetworking?

前端 未结 3 735
长情又很酷
长情又很酷 2021-02-05 22:56

Looking for an example of how to post json with AFHTTPClient. I see that there is a postPath method which takes an NSDictionary and the AFJSONEncode me

3条回答
  •  别那么骄傲
    2021-02-05 23:47

     - (NSMutableURLRequest *)requestByPostWithNSArrayToJSONArray:(NSArray *)parameters
    {
        NSURL *url = [NSURL URLWithString:@"" relativeToURL:self.baseURL];
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
        [request setHTTPMethod:@"POST"];
        [request setAllHTTPHeaderFields:self.defaultHeaders];
    
        if (parameters)
        {
                NSString *charset = (__bridge NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(self.stringEncoding));
                NSError *error = nil;
    
                [request setValue:[NSString stringWithFormat:@"application/json; charset=%@", charset] forHTTPHeaderField:@"Content-Type"];
    #pragma clang diagnostic push
    #pragma clang diagnostic ignored "-Wassign-enum"
                [request setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameters options:0 error:&error]];
    #pragma clang diagnostic pop
    
                if (error) {
                    NSLog(@"%@ %@: %@", [self class], NSStringFromSelector(_cmd), error);
                }
        }
    
        return request;
    }
    AFHTTPClient *httpClient = [[AFHTTPClient alloc]initWithBaseURL:[NSURL         URLWithString:URL_REGISTER_DEVICE]];
    NSArray *array = @[@"hello", @"world"];
    NSMutableURLRequest *request = [httpClient requestByPostWithNSArrayToJSONArray:array];
    
    
    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
    {
        NSLog(@"network operation succ");
    
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        NSLog(@"network operation fail");
    
    }];
    
    [operation start];
    

提交回复
热议问题