is there an example of AFHTTPClient posting json with AFNetworking?

前端 未结 3 742
长情又很酷
长情又很酷 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:34

    The best and simple way to do that is to subclass AFHTTPClient.

    Use this code snippet

    MBHTTPClient

    #define YOUR_BASE_PATH @"http://sample.com"
    #define YOUR_URL @"post.json"
    #define ERROR_DOMAIN @"com.sample.url.error"
    
    /**************************************************************************************************/
    #pragma mark - Life and Birth
    
    + (id)sharedHTTPClient
    {
        static dispatch_once_t pred = 0;
        __strong static id __httpClient = nil;
        dispatch_once(&pred, ^{
            __httpClient = [[self alloc] initWithBaseURL:[NSURL URLWithString:YOUR_BASE_PATH]];
            [__httpClient setParameterEncoding:AFJSONParameterEncoding];
            [__httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
            //[__httpClient setAuthorizationHeaderWithUsername:@"" password:@""];
        });
        return __httpClient;
    }
    
    /**************************************************************************************************/
    #pragma mark - Custom requests
    
    - (void) post<#Objects#>:(NSArray*)objects
    success:(void (^)(AFHTTPRequestOperation *request, NSArray *objects))success
    failure:(void (^)(AFHTTPRequestOperation *request, NSError *error))failure
    {
        [self postPath:YOUR_URL
           parameters:objects
              success:^(AFHTTPRequestOperation *request, id JSON){
                  NSLog(@"getPath request: %@", request.request.URL);
    
                  if(JSON && [JSON isKindOfClass:[NSArray class]])
                  {
                      if(success) {
                          success(request,objects);
                      }
                  }
                  else {
                      NSError *error = [NSError errorWithDomain:ERROR_DOMAIN code:1 userInfo:nil];
                      if(failure) {
                          failure(request,error);
                      }
                  }
              }
              failure:failure];
    }
    

    Then in your code just call

    [[MBHTTPClient sharedHTTPClient]  post<#Objects#>:objects
                                              success:^(AFHTTPRequestOperation *request, NSArray *objects) {
        NSLog("OK");
    }
                                              failure:(AFHTTPRequestOperation *request, NSError *error){
        NSLog("NOK %@",error);
    }
    

    objects is an NSArray (you can change it to NSDictonary) and will be encode in JSON format

    0 讨论(0)
  • 2021-02-05 23:42

    If you're posting to a JSON REST API, there should be a particular mapping from object property to JSON key, right? That is, the server is expecting certain information in certain named fields.

    So what you want to do is construct an NSDictionary or NSMutableDictionary with the keys used in the API and their corresponding values. Then, simply pass that dictionary into the parameters argument of any request method in AFHTTPClient. If the parameterEncoding property of the client is set to AFJSONParameterEncoding, then the body of the requests will automatically be encoded as JSON.

    0 讨论(0)
  • 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];
    
    0 讨论(0)
提交回复
热议问题