8

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

Right now I have:

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:

Error Domain=AFNetworkingErrorDomain Code=-1011 "Request failed: bad request (400)

3
  • any luck solving this?
    – bpn
    Feb 18, 2014 at 15:02
  • 1
    No, I just asked my backend guys to make all post requests in the body. That's what @mattt recommends.
    – barndog
    Feb 18, 2014 at 18:25
  • You can just format the URL yourself to include the parameters encoding, before sending it to the manager for the POST. This is what I ended up doing. Beware though that you really need to handle the encoding correctly if so (unless you're doing something simple like sending in a number or so).
    – BjornW
    Jan 21, 2019 at 13:32

6 Answers 6

23

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....

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.

You could override that and include POST as well.

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.

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

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

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....]];

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

1
  • I just added the POST in the HTTPMethodsEncodingParametersInURI and it worked thanks a lot.
    – AmJa
    Oct 23, 2014 at 19:33
3
#import "AFNetworking.h"
...
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *params = @{@"param1": value1,
                                 @"param2": value};
    manager.responseSerializer = [AFJSONResponseSerializer serializer]; // if response JSON format
    [manager POST:@"http://domain.com/backend.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {

    NSLog(@"%@", responseObject);
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];    
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    NSLog(@"%@", error);
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    }];

try this

2
  • Nah it's the same thing. Doing this puts the parameters in the body, not URI. Thanks though, twas a valid attempt. I think I'm just gonna have my backend guy change everything to body params.
    – barndog
    Dec 27, 2013 at 5:10
  • No, it's not same. When use in URL in php u received $_GET, for $_POST need send in body.
    – waki
    Dec 27, 2013 at 6:20
1

I've had the same problem with you.

Other people's answers seem to be accurate.

The cause of the error is:

when you init NSUrl with parameters such as http:www.baidu.com/api?id=1&name=我,it needs you to encode your urlString with utf-8

such as :

//解决奇葩需求:请求方式为post时,url带?id=1之类。主要原因是url带中文的时候url初始化失败 URLString = [URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError];

Hope to help you!

0

can you try this.

NSString* apiURL = @"http://example.com" 
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:apiURL]];
manager.responseSerializer = [AFJSONResponseSerializer serilizer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];

NSDictionary *parameters = @{@"name":@"John",@"date":"27/12/2013"};

AFHTTPRequestOperation *apiRequest = [manager POST:@"" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {


} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog@"response ---%@,responseObject";
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];

[apiRequest start];
0
0

I was able to do this by creating the string like this:

NSString *relativeURL =[NSString stringWithFormat:@"/reward/commit?deviceUUID=%@&rewardID=%@",[[Client sharedInstance] deviceUUID],self.rewardID];

and then passing it as the query. I had to set the requestSerializer and responseSerializer as follows:

client.requestSerializer = [AFJSONRequestSerializer serializer];
client.responseSerializer = [AFHTTPResponseSerializer serializer];

0

Worked for me once I left the manager.requestSerializer property alone and let it be the default (AFHTTPRequestSerializer). The service i was POSTing to, was seemingly expecting UTF8 encoded body parameters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.