18
编辑07/14AFNetworking - 如何使POST请求
正如比尔·伯吉斯在他回答的评论mentionned,这个问题是关系到AFNetworking
的version 1.3
。这里的新手可能已经过时了。
我是很新的iPhone的发展,我使用AFNetworking作为我的服务库。
我查询的API是REST风格的API,我需要发出POST请求。要做到这一点,我试着用下面的代码:
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:@"my_username", @"username", @"my_password", @"password", nil];
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/login"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(@"Pass Response = %@", JSON);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(@"Failed Response : %@", JSON);
}];
[operation start];
没有与此代码两个主要问题:
AFJSONRequestOperation
似乎使一个GET
请求,而不是一个POST
一个。- 我不能把参数放到这个方法中。
我也试图与此代码:
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:@"my_username", @"username", @"my_password", @"password", nil];
NSURL *url = [NSURL URLWithString:@"http://localhost:8080"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
[httpClient postPath:@"/login" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Succes : %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Failure : %@", error);
}];
有没有更好的办法,使我想在这里把它做?
感谢您的帮助!
感谢您的回复!只有一个问题:你的'SIOAPIClient'会在这里成为'MyAPIClient'吗? –
你是对的...我从我自己的实现中复制/粘贴这个,并且改变了类名。我猜想错过了一个地方。我编辑了我的答案,应该如何。 –
我试图像你写的那样实现一个自定义客户端,但是我得到一个错误:'没有选择器'sharedClient'的已知类方法。标题包含正确,所以我想知道为什么我得到这个错误。 –