如何使用AFNetworking为"PUT"请求设置数据?

Joh*_*son 2 iphone http objective-c ios afnetworking

我已经开始使用AFNetworking,它可以很好地进行简单的"GET"请求.但是现在我正在尝试进行"POST" - 请求.我使用下面的代码来执行"GET"请求.在查看AFHTTPClientputhPath时,无法设置要用于正文的数据.我的猜测是,有另一种解决方法.我一直在关注AFHTTPOperation作为解决这个问题的方法.但是,我没有让这个工作.问题是我不知道如何在基本身份验证中使用它.

有人可以给我一个如何用AFNetworking做一个简单的"POST"请求的提示吗?

AFHTTPClient* client = [AFHTTPClient clientWithBaseURL:ServerURL];
[client setAuthorizationHeaderWithUsername:self.username 
                                  password:self.password];

NSString* resourcePath = [NSString stringWithFormat:@"/some/resource/%@", 
                          endPath];

[client getPath:resourcePath 
     parameters:nil 
        success:^(AFHTTPRequestOperation *operation, id responseObject) {
            // Success code omitted
        } 
        failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            // Some error handling code omitted
        }
 ];
Run Code Online (Sandbox Code Playgroud)

Joh*_*son 13

我没有找到任何简单的方法来做到这一点.但我按照建议做了,并创建了自己的AFHTTPClient子类.在子类中,我实现了以下方法.这使得用我自己的数据执行POST请求和PUT请求成为可能.

- (void)postPath:(NSString *)path 
  parameters:(NSDictionary *)parameters 
        data:(NSData*)data
     success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
     failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
{
    NSURLRequest *request = [self requestWithMethod:@"POST" path:path     parameters:parameters data:data];
    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
    [self enqueueHTTPRequestOperation:operation];
}

- (void)putPath:(NSString *)path 
     parameters:(NSDictionary *)parameters 
           data:(NSData*)data
        success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
        failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
{
    NSURLRequest *request = [self requestWithMethod:@"PUT" path:path parameters:parameters data:data];
    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
[self enqueueHTTPRequestOperation:operation];
}

-(NSMutableURLRequest*)requestWithMethod:(NSString *)method 
                                    path:(NSString *)path 
                              parameters:(NSDictionary *)parameters 
                                 data:(NSData*)data;
{
    NSMutableURLRequest* request = [super requestWithMethod:method 
                                                      path:path 
                                                parameters:parameters];

    [request setHTTPBody:data];

    return request;
}
Run Code Online (Sandbox Code Playgroud)

  • 您无法再直接设置数据.解决方案:NSMutableURLRequest*request = [self requestWithMethod:@"POST"path:path parameters:parameters]; [请求setHTTPBody:data]; (3认同)