如何使用xml Body发送带有alamofire的请求

时间:2016-11-02 17:19:46

标签: ios xml swift alamofire swxmlhash

我在项目中安装了Alamofire,现在就是我所做的。

我安装了postman并将我的网址和内部的xml对象放在一起,我得到了我的结果。

这是我用邮递员完成的事情的图片

enter image description here

我现在如何使用Alamofire或SWXMLHash发送邮件时发送邮件

提前致谢!

修改

我从另一个问题尝试了这个:

 Alamofire.request(.POST, "https://something.com" , parameters: Dictionary(), encoding: .Custom({
            (convertible, params) in
            let mutableRequest = convertible.URLRequest.copy() as! NSMutableURLRequest

            let data = (self.testString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
            mutableRequest.HTTPBody = data
            return (mutableRequest, nil)
        }))


    .responseJSON { response in


    print(response.response) 

    print(response.result)   


    }
}

但它没有发送任何东西

这是日志:

  

可选({URL:   https://something.com} {状态代码:200,headers {       连接="保持活力&#34 ;;       " Content-Length的" = 349;       "内容类型" =" application / xml&#34 ;;       Date =" Wed,02 Nov 2016 21:13:32 GMT&#34 ;;       Server = nginx;       "严格,运输和安全" =" max-age = 31536000; includeSubDomains&#34 ;; }})

     

FAILURE

编辑

如果您没有简单的添加,请不要忘记通过参数,参数:Dictionary()

3 个答案:

答案 0 :(得分:6)

使用Swift 3和Alamofire 4

    let stringParams : String = "<msg id=\"123123\" reqTime=\"123123\">" +
        "<params class=\"API\">" + 
        "<param name=\"param1\">123213</param>" + 
        "<param name=\"param2\">1232131</param>" +
        "</params>" +
    "</msg>"

    let url = URL(string:"<#URL#>")
    var xmlRequest = URLRequest(url: url!)
    xmlRequest.httpBody = stringParams.data(using: String.Encoding.utf8, allowLossyConversion: true)
    xmlRequest.httpMethod = "POST"
    xmlRequest.addValue("application/xml", forHTTPHeaderField: "Content-Type")


    Alamofire.request(xmlRequest)
            .responseData { (response) in
                let stringResponse: String = String(data: response.data!, encoding: String.Encoding.utf8) as String!
                debugPrint(stringResponse)
    }

答案 1 :(得分:3)

使用Swift 3和Alamofire 4,您可以创建自定义ParameterEncoding。与任何其他XML编码主体一样,SOAP消息可以使用此参数编码,如以下示例所示。可以类似地创建其他XML正文编码(检查它所在的行urlRequest.httpBody = ...):

struct SOAPEncoding: ParameterEncoding {
    let service: String
    let action: String

    func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
        var urlRequest = try urlRequest.asURLRequest()

        guard let parameters = parameters else { return urlRequest }

        if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
            urlRequest.setValue("text/xml", forHTTPHeaderField: "Content-Type")
        }

        if urlRequest.value(forHTTPHeaderField: "SOAPACTION") == nil {
            urlRequest.setValue("\(service)#\(action)", forHTTPHeaderField: "SOAPACTION")
        }

        let soapArguments = parameters.map({key, value in "<\(key)>\(value)</\(key)>"}).joined(separator: "")

        let soapMessage =
            "<s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/' s:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'>" +
            "<s:Body>" +
            "<u:\(action) xmlns:u='\(service)'>" +
            soapArguments +
            "</u:\(action)>" +
            "</s:Body>" +
            "</s:Envelope>"

        urlRequest.httpBody = soapMessage.data(using: String.Encoding.utf8)

        return urlRequest
    }
}

然后像这样使用它:

Alamofire.request(url, method: .post, parameters: ["parameter" : "value"], encoding: SOAPEncoding(service: "service", action: "action"))

答案 2 :(得分:2)

假设您在请求中缺少有效的HTTP标头,更新的请求可能如下所示:

Alamofire.request(.POST, "https://something.com", parameters: Dictionary() , encoding: .Custom({
            (convertible, params) in
            let mutableRequest = convertible.URLRequest.copy() as! NSMutableURLRequest

            let data = (self.testString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
            mutableRequest.HTTPBody = data
            mutableRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
            return (mutableRequest, nil)
        }))
    .responseJSON { response in
    print(response.response) 
    print(response.result)   
    }
}

所以,基本上你应该添加一行

mutableRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")

<强>更新
尽量相同,但请使用responseDataresponseString代替responseJSON,因为您的回复可能不是JSON