我第一次使用AFNetworking
我需要将参数发送到.asmx
网络服务,这是我目前的代码:
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) {
...
这里没有问题,一切正常
但我想知道是否有更优雅的方式来添加参数?
像request.Parameters.Add("key", value);
答案 0 :(得分:1)
请尝试使用AFHTTPRequestOperationManager及其POST方法。
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);
}];