我想出了如何使用AFnetworking传递参数,但我很难弄清楚如何在我的API调用中传递body。目前这就是我的工作:
- (void)authenticateUser:(NSString *)username
password:(NSString *)password
success:(void (^) (NSString *accessToken))success
failure:(RequestFailureBlock)failure
{
NSString *authURL = @"http://someurlforauthentication";
NSDictionary *parameters = @{@"username" : username,
@"password" : password };
[self.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[self POST:authURL parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject){
NSString *accessToken = responseObject[@"access_token"];
// Store Access Token
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:accessToken forKey:APIAuthorizationToken];
[defaults synchronize];
NSLog(@"Hello %@", accessToken);
success(accessToken);
} failure:failure];
}
我需要做的是不传递任何参数,而是使用包含登录凭据的json字符串传递一个正文。像这样的东西
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
// Body
const char bytes[43] = "{\n \"username\": \"max\",\n \"password\": \"pass\"\n}";
request.HTTPBody = [NSData dataWithBytes:bytes length:43];
提前致谢。
答案 0 :(得分:9)
使用AFJSONRequestSerializer和AFJSONResponseSerializer,您可以按照自己的意愿行事。然后只需使用您用来发布的代码。整个过程应如下所示:
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration];
[manager setRequestSerializer:[AFJSONRequestSerializer serializer]];
[manager setResponseSerializer:[AFJSONResponseSerializer serializer]];
NSDictionary *parameters = @{@"test": @"this is a test"};
[manager POST:@"http://localhost:8080/TestRequest/test" parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(@"%@",[responseObject description]);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(@"%@",[error localizedDescription]);
}];