AFNetworking 2.0使用URL参数发送发布请求 [英] AFNetworking 2.0 Send Post Request with URL Parameters

查看:204
本文介绍了AFNetworking 2.0使用URL参数发送发布请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 AFNetworking 2.0发送 POST 请求,其中包含URL中的所有参数:

How do I send a POST request with AFNetworking 2.0 with all the parameters in the URL like such:

http://www.myserver .com?api_key = something& lat = 2.4& radius = 100

现在我有:

NSString* query = @"http://example.com?name=param&date=param";
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{};
[manager POST:query parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

但是它没有用,我收到了这个错误:

But it's not working, I get this error back:

错误域= AFNetworkingErrorDomain代码= -1011请求失败:错误请求(400)

推荐答案

之前的最佳答案是让后端更改并接受正文中的参数。这是首选方法,但有时我们中的一些人使用后端无法改变,所以我提供这个解决方案....

The previous best answer was to get the backend to change and accepts parameters in the body. Thats the preferred method but sometimes some of us are stuck using backends that can't change so I offer this solution....

在类AFURLRequestSerialization中有一个名为HTTPMethodsEncodingParametersInURI的属性,它是一个NSSet,它包含允许在uri中使用params的http方法 GET HEAD ,默认情况下 DELETE

In the class AFURLRequestSerialization there is a property called HTTPMethodsEncodingParametersInURI and that is an NSSet that contains the http methods that are allowed to use params in the uri GET, HEAD, and DELETE by default.

您可以覆盖它并包含POST。

You could override that and include POST as well.

在AFURLRequestSerialization.m中,第462行有一个if语句来检查自己.HTTPMethodsEncodingParametersInURI属性包含POST。如果没有(因为它)默认情况下不会),它会将参数放在正文中。

in AFURLRequestSerialization.m lines 462 has an if statement that checks self.HTTPMethodsEncodingParametersInURI property contains POST. if it doesn't (as it doesn't by default), it will put the parameters in the body.

您可以注释掉该id语句以进行快速测试。

You can comment out that id statement for a quick test.

为了让它工作,我建议覆盖HTTPMethodsEncodingParametersInURI属性。

To get it to work I recommend overwriting the HTTPMethodsEncodingParametersInURI property.

设置你的AFHTTPSessionManager它应该是这样的......

when setting up your AFHTTPSessionManager it should look like this...

  AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:self.httpBaseUrl]];
   manager.requestSerializer = [AFHTTPRequestSerializer serializer];
   manager.requestSerializer.HTTPMethodsEncodingParametersInURI = [NSSet setWithArray:@[@"POST", @"GET", @"HEAD", whatever other http methods you need here....]];

这应该允许在POST的uri中发送参数。为我工作,希望它可以帮助别人

this should allow for sending a parameters in the uri of a POST. worked for me, hope it helps someone else

这篇关于AFNetworking 2.0使用URL参数发送发布请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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