在Swift iPhone应用程序中请求SOAP Web服务时出现XMLStreamreader错误

时间:2015-08-17 11:29:02

标签: ios iphone swift soap

我正在尝试从Swift中的代码中使用SOAP Web服务,但我得到了以下响应:

Optional(<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"><soap:Body><soap:Fault><soap:Code><soap:Value>soap:Sender</soap:Value></soap:Code><soap:Reason><soap:Text xml:lang="en">Error reading XMLStreamReader: Unexpected EOF in prolog at [row,col {unknown-source}]: [1,38]</soap:Text></soap:Reason></soap:Fault></soap:Body></soap:Envelope>)

SOAP请求:

var soapMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
    "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\""
    "xmlns:v1=\"http://xxx/SecurityServiceWSDLType/V1\""
    "xmlns:v11=\"http://xxx/Security/V1\">"
    "<soap:Header/>"
    "<soap:Body>"
    "<v1:Authenticate>"
    "<v1:UserLoginDetails>"
    "<v11:UserId>aaa</v11:UserId>"
    "<v11:Password>aaa</v11:Password>"
    "</v1:UserLoginDetails>"
    "</v1:Authenticate>"
    "</soap:Body>"
    "</soap:Envelope>"

    //var soapMessage = text
    var url = NSURL(string: wsUrl)
    var theRequest = NSMutableURLRequest(URL: url!)
    var msgLength = String(count(soapMessage))

    theRequest.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
    theRequest.addValue(msgLength, forHTTPHeaderField: "Content-Length")
    theRequest.HTTPMethod = "POST"
    theRequest.HTTPBody = soapMessage.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) // or false

    var connection = NSURLConnection(request: theRequest, delegate: self, startImmediately: true)
    connection?.start()

    if(connection == true){
        var mutableData : Void = NSMutableData.initialize()
    }

为什么我收到此错误?我已经使用Chrome中的postmaster插件检查了SOAP请求,但它工作正常,但是当我从iOS代码访问它时,我遇到了上述错误。

1 个答案:

答案 0 :(得分:0)

如果您打印出soapMessage,您会看到它只有prolog:

println(soapMessage)

结果

<?xml version="1.0" encoding="utf-8"?>

你需要连接字符串:

var soapMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  + "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\""
  + "xmlns:v1=\"http://xxx/SecurityServiceWSDLType/V1\""
  + "xmlns:v11=\"http://xxx/Security/V1\">"
  + "<soap:Header/>"
  + "<soap:Body>"
  + "<v1:Authenticate>"
  + "<v1:UserLoginDetails>"
  + "<v11:UserId>aaa</v11:UserId>"
  + "<v11:Password>aaa</v11:Password>"
  + "</v1:UserLoginDetails>"
  + "</v1:Authenticate>"
  + "</soap:Body>"
  + "</soap:Envelope>"