如何使用AFNetworking 2.0与application / x-www-form-urlencoded HttpHeaderField发布数据

时间:2015-10-04 16:35:36

标签: ios objective-c json afnetworking nsurlconnection

我要将NSURLConnection转换为AFNetworking 2.0。当我使用NSURLConnection发布工作正常的数据。但我不知道如何使用AFNetworking 2.0。

这是NSURLConnection请求的代码片段。

#define API_URL @https://myurl.com//login.php"

#define LOGIN_POST_TYPE @"app_data={\"app_data\":{\"user\":\"%@\",\"password\":\"%@\"}}"
+(void) post:(NSString*)api AndPostData:(NSData*)postData AndCallback: (void (^)(id result, NSError *error))callback {

    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
    [request setURL:[NSURL URLWithString:API_URL];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

    [request setTimeoutInterval:10.0];
    [request setHTTPBody:postData];

    NSOperationQueue *queue = [[NSOperationQueue alloc] init];

    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
    {
        NSLog(@"%@",response);
        if ([data length] >0 && connectionError == nil)
        {
            NSString *dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            callback([dataStr JSONValue], nil);
        }
        else
        {
            callback(nil, connectionError);
        }
    }];

}


+(void) callAPIWithType:(int)apiType withParams:(NSDictionary *)param andCallback:(void(^)(id result, NSError *error)) callback
{

NSString *strPost = [NSString stringWithFormat:LOGIN_POST_TYPE, param[@"email"], param[@"password"]];

NSLog(@"%@", post);

NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

    [self post:API_URL AndPostData:postData AndCallback:^(id result, NSError *error) {
         callback(result, error);
    }];
}

就像我说的,这段代码运行正常。但是如何将此代码转换为AFNetworking 2.0? 我用AFNetworking做了很多尝试。但是所有方式都不适合我。 我收到错误回复。

我该怎么做?

1 个答案:

答案 0 :(得分:0)

下面是我使用的代码示例,但更改为符合您的请求,您的postData只需NSDictionary而不是NSData ...

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

[manager setRequestSerializer:[AFJSONRequestSerializer serializer]];

[manager POST:@"https://myurl.com//login.php" parameters:postData success:^(AFHTTPRequestOperation *operation, id responseObject) {

  // responseObject contains the result

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         NSLog(@"%@ failed: %@",NSStringFromClass([self class]),operation.responseObject);

}];