gpt4 book ai didi

ios - AFHTTPSessionManager 子类 : Post API with body.

转载 作者:可可西里 更新时间:2023-11-01 06:23:09 26 4
gpt4 key购买 nike

我想出了如何使用 AFnetworking 传递参数,但我很难弄清楚如何在我的 API 调用中传递正文。目前这就是我所做的:

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

提前致谢。

最佳答案

使用 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]);
}];

关于ios - AFHTTPSessionManager 子类 : Post API with body.,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23141332/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com