【问题标题】:How to send XML POST request using AFNetworking如何使用 AFNetworking 发送 XML POST 请求
【发布时间】:2013-06-24 01:20:16
【问题描述】:

阅读了大量的答案,但没有找到一个简单的答案: 如何通过 POST 和使用 AFNetworking 将简单的 XML 发送到 URL?

<?xml version=’1.0’ encoding=’UTF-­‐8’?>
<data>
<login>LOGIN</login>
<password>PASSWORD</password>
</data>

网址例如:http://example.com/API/balance.php

当我使用时:

NSDictionary *params = @{@"login":@"login",@"password":@"password"};
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
[client setDefaultHeader:@"Content-Type" value:@"application/xml"];
[client postPath:@"balance.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
... some code ...
}failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error retrieving data: %@", error);
}];

我总是从 API 获取带有错误的 XML:第 1 行中的错误不是格式正确(无效令牌)

当我使用 HTTP 嗅探器时,我看到 Content-Type:application/x-www-form-urlencoded;字符集=utf-8

可能是这个问题,但我不知道。 将 php 与 curl 一起使用 - 从 API 获得正确答案。

任何人都可以展示这个 XML 请求和 URL 的工作示例吗?

【问题讨论】:

    标签: ios objective-c xml post afnetworking


    【解决方案1】:

    这是因为默认的[AFHTTPClient parameterEncoding]AFFormURLParameterEncoding。不幸的是,没有 AFXMLParameterEncoding 这样的编码,所以我会手动创建 XML 并将其设置在 NSMutableURLRequest 上:

    AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
    [client setDefaultHeader:@"Content-Type" value:@"application/xml"];
    
    NSString *xml = [NSString stringWithFormat:@"<?xml version=’1.0’ encoding='UTF-­‐8'?><data><login>%@</login><password>%@</password></data>", user, password];
    NSMutableURLRequest *req = [self requestWithMethod:@"POST" path:@"autenticacao" parameters:nil];
    req.HTTPBody = [xml dataUsingEncoding:NSUTF8StringEncoding];
    
    AFKissXMLRequestOperation *op = [AFKissXMLRequestOperation XMLDocumentRequestOperationWithRequest:req success:^(NSURLRequest *request, NSHTTPURLResponse *response, DDXMLDocument *XMLDocument) {
    
        NSLog(@"%@", XMLDocument);
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, DDXMLDocument *XMLDocument) {
        NSLog(@"%@", error);
    }];
    [client enqueueHTTPRequestOperation:op];
    

    我还在使用AFKissXMLRequestOperation,它是AFNetworking 的扩展,可以更轻松地解析响应中的 XML。

    【讨论】:

    • 非常感谢马塞洛。它确实帮助我进行了一些更改。 (我从字符串 "encoding='UTF-8'" 的 "
    • AFKissXMLRequestOperation 扩展已正式弃用。
    【解决方案2】:

    在您的client 上,请务必设置要使用的请求操作类型:

    [client registerHTTPOperationClass:[AFXMLRequestOperation class]];
    

    【讨论】:

    • 没什么变化,同样的 API 错误和 Header 有 Content-type:application/x-www-form-urlencoded; charset=utf-8
    猜你喜欢
    • 1970-01-01
    • 2012-07-02
    • 2016-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-30
    • 1970-01-01
    • 2016-09-03
    相关资源
    最近更新 更多