AFNetworking 2.0的POST请求无效,但在HTTP请求测试程序中工作 [英] POST Request with AFNetworking 2.0 not working, but working in HTTP Request tester

查看:108
本文介绍了AFNetworking 2.0的POST请求无效,但在HTTP请求测试程序中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始使用新的 AFNetworking 2.0 API,暂时使用了以前的版本。我正在尝试做一个沼泽标准 http POST请求,但遗憾的是我做得不太好。这是我目前的代码:

I've just started using the new AFNetworking 2.0 API having used the previous versions for a while now. I'm trying to do a bog standard http POST request, but sadly I'm not doing too well. This is my current code:

AFHTTPRequestOperationManager *operationManager = [AFHTTPRequestOperationManager manager];

NSDictionary *parameters = @{@"username" : self.usernameField.text,
                             @"password" : self.passwordField.text};

[operationManager POST:@"https:URL GOES HERE" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", [responseObject description]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

现在返回 JSON (NULL)并且没有给我一个状态代码,如 404 或其他东西(顺便提一下我们如何获得状态代码使用AFN 2.0?)。但是,当我尝试使用 apikitchen.com 等网络应用程序来测试 HTTP Post请求时对我来说,当我将用户名和密码放在 param 字段中时,它会起作用。所以我的问题是,为什么 AFN 2.0参数属性中的参数的行为方式与网络应用中的参数?更一般地说, AFN 2.0

Now this returns a JSON of (NULL) and doesn't give me a status code like 404 or something (incidentally how do we attain the status code when using AFN 2.0?). However, when I try the information with a web app like apikitchen.com which tests the HTTP Post request for me, it works when I put the username and password in the param field. So really my question is, why don't the parameters in the AFN 2.0 parameter property act in the same way as the parameters in the web app? And more generally why aren't the post request parameters working for me in AFN 2.0?

感谢您提前获得帮助,

Mike

Thanks for the help in advance,
Mike

编辑:我'我正在努力实施建议的解决方案。我的Post方法现在看起来像这样,但它现在对我没有意义。

I'm struggling with the implementation of the suggested fix. My Post method now looks like this, but It doesn't make sense to me right now.

AFHTTPRequestOperationManager *operationManager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"username" : self.usernameField.text,
                             @"password" : self.passwordField.text};

operationManager.requestSerializer.queryStringSerializationWithBlock =
^NSString*(NSURLRequest *request,
           NSDictionary *parameters,
           NSError *__autoreleasing *error) {
    NSString* encodedParams = form_urlencode_HTTP5_Parameters(parameters);
    return encodedParams;
};

[operationManager POST:@"URL HERE" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", [responseObject description]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];


推荐答案


现在返回一个(NULL)的JSON,并没有给我像404或其他东西的状态代码(顺便说一下,我们如何获得使用AFN 2.0时的状态代码?)。

Now this returns a JSON of (NULL) and doesn't give me a status code like 404 or something (incidentally how do we attain the status code when using AFN 2.0?).

至少应该给出错误。故障处理程序打印出来的是什么?

It should at least give an error. What does the failure handler print out?


所以我的问题是,为什么AFN 2.0参数属性中的参数不起作用与Web应用程序中的参数相同?更一般地说为什么AFN 2.0中的post请求参数不适合我?

So really my question is, why don't the parameters in the AFN 2.0 parameter property act in the same way as the parameters in the web app? And more generally why aren't the post request parameters working for me in AFN 2.0?

在检查AFN(版本2.0.1)之后)编码参数,在我看来,这些参数不是按照它们应该编码的: application / x-www-form-urlencoded编码算法

After examining how AFN (Version 2.0.1) encodes the parameters, it appears to me that these aren't encoded as they should: The application/x-www-form-urlencoded encoding algorithm.

在此问题得到解决之前,您可以尝试以下解决方法。以下算法严格按照w3c对HTTP 5的建议对参数进行编码,至少对于Mac OS X 10.8,我测试过它:

Until this has been fixed, you may try the following workaround. The following algorithm encodes parameters strictly as suggested by w3c for HTTP 5, at least for Mac OS X 10.8 where I've tested it:

static NSString* form_urlencode_HTTP5_String(NSString* s) {
    CFStringRef charactersToLeaveUnescaped = CFSTR(" ");
    CFStringRef legalURLCharactersToBeEscaped = CFSTR("!$&'()+,/:;=?@~");

    NSString *result = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
                         kCFAllocatorDefault,
                         (__bridge CFStringRef)s,
                         charactersToLeaveUnescaped,
                         legalURLCharactersToBeEscaped,
                         kCFStringEncodingUTF8));
    return [result stringByReplacingOccurrencesOfString:@" " withString:@"+"];
}

(注意:上面的代码取决于函数<$ c的实现细节$ c> CFURLCreateStringByAddingPercentEscapes 。完全有可能轻松实现建议的算法,没有任何依赖关系,我建议 - 它变得不那么短。)

(Note: the code above depends on the implementation details of function CFURLCreateStringByAddingPercentEscapes. It's entirely possible to implement the suggested algorithm easily without any dependencies, which I would recommend - it becomes just not that short.)

static NSString* form_urlencode_HTTP5_Parameters(NSDictionary* parameters) 
{
    NSMutableString* result = [[NSMutableString alloc] init];
    BOOL isFirst = YES;
    for (NSString* name in parameters) {
        if (!isFirst) {
            [result appendString:@"&"];
        }
        isFirst = NO;
        assert([name isKindOfClass:[NSString class]]);
        NSString* value = parameters[name];
        assert([value isKindOfClass:[NSString class]]);

        NSString* encodedName = form_urlencode_HTTP5_String(name);
        NSString* encodedValue = form_urlencode_HTTP5_String(value);

        [result appendString:encodedName];
        [result appendString:@"="];
        [result appendString:encodedValue];
    }

    return [result copy];
}

然后,使用AFN时,您可以自定义序列化算法,如下所示:

Then, when using AFN, you can customize the serializing algorithm as shown below:

    AFHTTPRequestOperationManager *operationManager = [AFHTTPRequestOperationManager manager];

    operationManager.requestSerializer.queryStringSerializationWithBlock = 
       ^NSString*(NSURLRequest *request,
                  NSDictionary *parameters,
                  NSError *__autoreleasing *error) {
        NSString* encodedParams = form_urlencode_HTTP5_Parameters(parameters);
        return encodedParams;
    };

这篇关于AFNetworking 2.0的POST请求无效,但在HTTP请求测试程序中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆