简体   繁体   中英

Unable to set body in AFNetworking 3.0

I need to set {"token":"asdfwrwer234234d"} as http body.

self.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];

[self.requestSerializer setValue:Token forHTTPHeaderField:@"Token"];

[self POST:[NSString stringWithFormat:@"%@2/9/1",BaseURL] parameters:nil
  progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

    completion(responseObject,YES);

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

}];

It resolve my problem :

NSDictionary *body = @{@"token":Token};
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]];


AFHTTPResponseSerializer *responseManager = [AFHTTPResponseSerializer serializer];

responseManager.acceptableContentTypes = [NSSet setWithObject:@"text/html"];

manager.responseSerializer = responseManager;

NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"%@2/9/1",BaseURL] parameters:nil error:nil];

req.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue];
[req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];


[[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {

    if (!error) {
        NSError* error;
        NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseObject
                                                             options:kNilOptions
                                                               error:&error];

    } else {
        NSLog(@"Error: %@, %@, %@", error, response, responseObject);
    }
}] resume];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM