1110
1110

Reputation: 6839

How to add parameters to request object instead building string - AFNetworking

I am using AFNetworking for the first time.
I need to send parameters to .asmx web service this is my code so far:

NSString *soapMessage =
    [NSString stringWithFormat:
     @"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
     "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
     "<soap:Body>"
     "<AuthenticateUser xmlns=\"http://www.domain.com/\">"
     "<username>%@</username>"
     "<password>%@</password>"
     "</AuthenticateUser>"
     "</soap:Body>"
     "</soap:Envelope>", username, password
     ];

    NSString *BaseURLString = [NSString stringWithFormat:@"http://.../mywebservice.asmx"];
    NSURL *url = [NSURL URLWithString:BaseURLString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

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

    [request addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [request addValue: msgLength forHTTPHeaderField:@"Content-Length"];

    [request setHTTPMethod:@"POST"];
    [request setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

    // Make sure to set the responseSerializer correctly
    operation.responseSerializer = [AFXMLParserResponseSerializer serializer];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
...

There is no problem here it all works fine.
But I am wondering is there some more elegant way to add parameters?
Something like request.Parameters.Add("key", value);

Upvotes: 1

Views: 1083

Answers (1)

mocarz
mocarz

Reputation: 11

Please try using AFHTTPRequestOperationManager and its POST method.

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFXMLParserResponseSerializer serializer];

NSDictionary *parameters = @{@"foo": @"bar"};
[manager POST:@"http://example.com/resources.xml" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"response: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

https://github.com/AFNetworking/AFNetworking

Upvotes: 1

Related Questions