如何使用android-ksoap2构建正确的XML请求?

时间:2018-01-27 15:19:01

标签: java android xml ksoap2 android-ksoap2

我正在尝试从Android项目调用web服务,但我无法传递任何参数。

我需要建立一个这样的请求:

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="www.mywebservice.com">
  <SOAP-ENV:Body>
    <ns1:MyMethodName>
      <ns1:appUser>0</ns1:appUser>
    </ns1:MyMethodName>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

但是使用kso​​ap2,我得到这样的结果:

<v:Envelope xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:d="http://www.w3.org/2001/XMLSchema" xmlns:c="http://schemas.xmlsoap.org/soap/encoding/" xmlns:v="http://schemas.xmlsoap.org/soap/envelope/">
  <v:Header />
  <v:Body>
    <MyMethodName xmlns="www.mywebservice.com">
      <appUser>0</appUser>
    </MyMethodName>
  </v:Body>
</v:Envelope>

我的代码是:

SoapObject request = new SoapObject(NAMESPACE,METHOD_NAME);
request.addProperty("appUser",0);

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setAddAdornments(false);
envelope.implicitTypes = true;

envelope.setOutputSoapObject(request);

HttpTransportSE httpTransport = new HttpTransportSE(URL);
httpTransport.debug = true;

httpTransport.call(SOAP_ACTION, envelope);

尝试了很多示例,但似乎没有任何工作 - 我无法构建正确的XML请求。

1 个答案:

答案 0 :(得分:0)

我解决了这个问题:

  1. 创建了一个新类,它扩展了 SoapSerializationEnvelope 并覆盖了它的方法 write - 我已经修改了它以满足我的需求:

    public class MyNewClass extends SoapSerializationEnvelope {
    
            public MyNewClass (int version) {
                super(version);
            }
    
            @Override
            public void write(XmlSerializer writer) throws IOException {
                env = "http://schemas.xmlsoap.org/soap/envelope/";
                String tem = "www.mywebservice.com";
                writer.startDocument("UTF-8", true);
                writer.setPrefix("SOAP-ENV", env);
                writer.setPrefix("ns1", tem);
                writer.startTag(env, "Envelope");
                writer.startTag(env, "Body");
                writer.startTag(tem, "MyMethodName");
                writeBody(writer);
                writer.endTag(tem, "MyMethodName");
                writer.endTag(env, "Body");
                writer.endTag(env, "Envelope");
                writer.endDocument();
            }
        }
    
  2. 而不是使用 SoapSerializationEnvelope

    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    
  3. 我使用我新创建的类:

    MyNewClass envelope = new MyNewClass (SoapEnvelope.VER11);