ios 使用 AFNetworking 进行异步 POST json 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15290761/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 22:37:12  来源:igfitidea点击:

Using AFNetworking for asynchronous POST json requests

iosafnetworking

提问by Jonathan

I've been trying to use POST json using AFNetworking. After some research I finally got this to work

我一直在尝试使用 AFNetworking 使用 POST json。经过一番研究,我终于得到了这个工作

- (IBAction)go:(id)sender {
    //Some POST
    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"https://www.test.com/"]];
    [httpClient setParameterEncoding:AFJSONParameterEncoding];
    NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST"
                                                            path:@"https://www.test.com/user/login/"
                                                      parameters:@{@"username":self.username.text, @"password":self.password.text}];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        // Print the response body in text
        NSDictionary *jsonDict = (NSDictionary *) responseObject;
        BOOL *success = [[jsonDict objectForKey:@"success"] boolValue];
        NSLog(@"Response: %@", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
    [operation start];
}

This is fine for demonstation purposes, but now I want to finally use NSDirectory to split out my json objects, so I tried doing something like this, but my app crashes whenever I enter click on the button

这对于演示目的很好,但现在我想最终使用 NSDirectory 来拆分我的 json 对象,所以我尝试做这样的事情,但是每当我输入单击按钮时,我的应用程序就会崩溃

- (IBAction)go:(id)sender {
    //Some POST
    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"https://www.test.com/"]];
    [httpClient setParameterEncoding:AFJSONParameterEncoding];
    NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST"
                                                            path:@"https://www.test.com/user/login/"
                                                      parameters:@{@"username":self.username.text, @"password":self.password.text}];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        // Print the response body in text
        NSDictionary *jsonDict = (NSDictionary *) responseObject;
        BOOL success = [[jsonDict objectForKey:@"success"] boolValue];
        if (success) {
            NSLog(@"yes!!!");
        }else{
            NSString *reason = [jsonDict objectForKey:@"reason"];
            NSLog(@"reason: %@",reason);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
    [operation start];
}

error

错误

2013-03-08 03:27:34.648 test[18253:c07] -[__NSCFData objectForKey:]: unrecognized selector sent to instance 0x888a6b0
2013-03-08 03:27:34.648 test[18253:c07] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFData objectForKey:]: unrecognized selector sent to instance 0x888a6b0'
*** First throw call stack:
(0x1ce0012 0x111de7e 0x1d6b4bd 0x1ccfbbc 0x1ccf94e 0x24608 0x12e71 0x4a4453f 0x4a56014 0x4a467d5 0x1c86af5 0x1c85f44 0x1c85e1b 0x1c3a7e3 0x1c3a668 0x61ffc 0x21ad 0x20d5)
libc++abi.dylib: terminate called throwing an exception

回答by rckoenes

You are using AFHTTPRequestOperationand not AFJSONRequestOperation.

您正在使用AFHTTPRequestOperation而不是AFJSONRequestOperation.

Also you can use the AFHttpClientdirectly:

您也可以AFHttpClient直接使用:

NSDictionary *parameter = @{@"username":self.username.text, @"password":self.password.text};
[httpClient setParameterEncoding:AFJSONParameterEncoding];
[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];

[httpClient postPath:@"api/v1/user/login/" parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
    // Print the response body in text
    BOOL *success = [[responseObject objectForKey:@"success"] boolValue];
    NSLog(@"Response: %@",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    [self handleConnectionError:error];
}];

I would also suggest creating a creating only one instance of the AFHTTPClientusing clientWithBaseURL:method.

我还建议创建一个只创建AFHTTPClientusingclientWithBaseURL:方法的一个实例。

回答by sarra srairi

with AFHTTPRequestOperationManager you will add your request manager in my case i've done a POST Method with NSdictionnary as a parameters

使用 AFHTTPRequestOperationManager 你将添加你的请求管理器在我的例子中我已经完成了一个 POST 方法,使用 NSdictionnary 作为参数

[manager GET:url parameters:parameters success:success failure:failure];

with this line you can choose your Method / GET OR POST

使用这一行,您可以选择您的方法/获取或发布

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters= dic;
NSMutableString *url = [[NSMutableString alloc] init];
[url appendString: RootObj.root];
    [url appendString:@"/yourURL/"];
manager.requestSerializer=[AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];

[manager POST:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {      
}];
}

回答by sarra srairi

I was trying to send JSON object and getting back JSON data and parse it

我试图发送 JSON 对象并取回 JSON 数据并解析它

NSURL *url = [NSURL URLWithString:@"https://MySite.com/"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc]initWithBaseURL:url];
//[httpClient setParameterEncoding:AFJSONParameterEncoding];
//[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];

NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                        @"Ans", @"name",
                        @"29",  @"age", nil];
NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST"
                                                        path:@"/testJSONReturn.php"
                                                  parameters:params];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
    NSLog(@"DATA: %@", [JSON valueForKeyPath:@"data"]);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
    NSLog(@"Request Failure Because %@",[error userInfo]);
}];

[operation start];

Might help

可能有帮助

回答by lbsweek

another method, using AFHTTPRequestOperation:

另一种方法,使用 AFHTTPRequestOperation:

NSString* path = "http://www.test.com/file.php";
NSMutableURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:path]];
//request.HTTPMethod = @"GET";
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
//operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"success: %@", operation.responseString);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"error: %@",  operation.responseString);
}];
[operation start];