ios AFNetworking - 如何发出 POST 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11294769/
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 19:05:46  来源:igfitidea点击:

AFNetworking - How to make POST request

iphoneobjective-ciosjsonafnetworking

提问by Nugget

EDIT 07/14

编辑 07/14

As Bill Burgess mentionned in a comment of his answer, this question is related to the version 1.3of AFNetworking. It may be outdated for the newcomers here.

正如比尔·伯吉斯在他回答的评论mentionned,这个问题是有关version 1.3AFNetworking。对于这里的新人来说可能已经过时了。



I'm quite new to iPhone development, and I'm using AFNetworking as my services library.

我对 iPhone 开发很陌生,我使用 AFNetworking 作为我的服务库。

The API i'm querying is a RESTful one, and I need to make POST requests. To do this, I tried with the following code :

我查询的 API 是 RESTful 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];

There are two main issues with this code :

这段代码有两个主要问题:

  • AFJSONRequestOperationseems to make a GETrequest, not a POSTone.
  • I can't put parameters to this method.
  • AFJSONRequestOperation似乎是在提出GET请求,而不是提出请求POST
  • 我不能给这个方法添加参数。

I also tried with this code :

我也试图与此代码:

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

Is there a better way to make what I want here to get it done ?

有没有更好的方法来制作我想要的东西来完成它?

Thanks for the help !

谢谢您的帮助 !

回答by Bill Burgess

You can override the default behavior of your request being used with AFNetworkingto process as a POST.

您可以覆盖用于AFNetworking作为 POST 处理的请求的默认行为。

NSURLRequest *request = [client requestWithMethod:@"POST" path:path parameters:nil];

This assumes you have overridden the default AFNetworkingsetup to use a custom client. If you aren't, I would suggest doing it. Just create a custom class to handle your network client for you.

这假设您已覆盖默认AFNetworking设置以使用自定义客户端。如果你不是,我建议你这样做。只需创建一个自定义类来为您处理网络客户端。

MyAPIClient.h

我的APIClient.h

#import <Foundation/Foundation.h>
#import "AFHTTPClient.h"

@interface MyAPIClient : AFHTTPClient

+(MyAPIClient *)sharedClient;

@end

MyAPIClient.m

我的APIClient.m

@implementation MyAPIClient

+(MyAPIClient *)sharedClient {
    static MyAPIClient *_sharedClient = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        _sharedClient = [[self alloc] initWithBaseURL:[NSURL URLWithString:webAddress]];
    });
    return _sharedClient;
}

-(id)initWithBaseURL:(NSURL *)url {
    self = [super initWithBaseURL:url];
    if (!self) {
        return nil;
    }
    [self registerHTTPOperationClass:[AFJSONRequestOperation class]];
    [self setDefaultHeader:@"Accept" value:@"application/json"];
    self.parameterEncoding = AFJSONParameterEncoding;

    return self;

}

Then you should be able to fire off your network calls on the operation queue with no problem.

然后,您应该能够毫无问题地在操作队列上触发网络调用。

    MyAPIClient *client = [MyAPIClient sharedClient];
    [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
    [[AFNetworkActivityIndicatorManager sharedManager] incrementActivityCount];

    NSString *path = [NSString stringWithFormat:@"myapipath/?value=%@", value];
    NSURLRequest *request = [client requestWithMethod:@"POST" path:path parameters:nil];

    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        // code for successful return goes here
        [[AFNetworkActivityIndicatorManager sharedManager] decrementActivityCount];

        // do something with return data
    }failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        // code for failed request goes here
        [[AFNetworkActivityIndicatorManager sharedManager] decrementActivityCount];

        // do something on failure
    }];

    [operation start];