2016-02-17 2 views
0

Я использую Eclipse Indigo для создания приложения Android для вызова веб-сервиса. Это уже работает над проектом Java, но я знаю, что это совсем другое дело.Как бороться с WSDL complexType при разработке приложений для Android?

Я знаю, что вы можете использовать библиотеку ksoap2 и вызывать WebService так:

SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); 
request.addProperty("something","Somevalue"); 

Но я не знаю, как вызвать веб-сервис, когда ваш WSDL имеет ComplexType, как следующее:

<?xml version='1.0' encoding='UTF-8'?> 
<definitions name='Gator' targetNamespace='http://home.com/gatorws/ws/Gator/' xmlns='http://schemas.xmlsoap.org/wsdl/' xmlns:soap='http://schemas.xmlsoap.org/wsdl/soap/' xmlns:tns='http://home.com/gatorws/ws/Gator/' xmlns:xsd='http://www.w3.org/2001/XMLSchema'> 
<types> 
    <xs:schema targetNamespace='http://home.com/gatorws/ws/Gator/' version='1.0' xmlns:tns='http://home.com/gatorws/ws/Gator/' xmlns:xs='http://www.w3.org/2001/XMLSchema'> 
    <xs:element name='Gator'> 
    <xs:complexType> 
    <xs:sequence> 
     <xs:element name='idBus' type='tns:IdBusCT'/> 
     <xs:element name='infoGPS' type='tns:InfoGPSCT'/> 
     <xs:element name='infoBus' type='tns:InfoBusCT'/> 
     <xs:element name='infoMore' type='tns:InfoMoreCT'/> 
     <xs:element maxOccurs='unbounded' minOccurs='0' name='msjcs' nillable='true' type='tns:Mesaje'/> 
     <xs:element name='msjOPT' type='tns:MsjCor'/> 
    </xs:sequence> 
    </xs:complexType> 
    </xs:element> 
    <xs:element name='GatorFault'> 
    <xs:complexType> 
    <xs:sequence> 
     <xs:element name='result' type='xs:int'/> 
     <xs:element name='msj' type='xs:string'/> 
    </xs:sequence> 
    </xs:complexType> 
    </xs:element> 
    <xs:element name='GatorResponse'> 
    <xs:complexType> 
    <xs:sequence> 
     <xs:element name='result' type='tns:Result'/> 
    </xs:sequence> 
    </xs:complexType> 
    </xs:element> 
    <xs:complexType name='IdBusCT'> 
    <xs:sequence> 
    <xs:element name='idOp' type='xs:int'/> 
    <xs:element name='codBus' nillable='true' type='xs:string'/> 
    <xs:element name='codEqu' nillable='true' type='xs:string'/> 
    <xs:element name='codType' type='xs:int'/> 
    </xs:sequence> 
    </xs:complexType> 
    <xs:complexType name='InfoGPSCT'> 
    <xs:sequence> 
    <xs:element name='lat' type='xs:double'/> 
    <xs:element name='lng' type='xs:double'/> 
    <xs:element name='date' type='xs:string'/> 
    <xs:element name='direction' type='xs:int'/> 
    <xs:element name='valid' type='xs:int'/> 
    <xs:element name='velocity' type='xs:double'/> 
    </xs:sequence> 
    </xs:complexType> 
    <xs:complexType name='InfoBusCT'> 
    <xs:sequence> 
    <xs:element default='1' name='ignition' nillable='true' type='xs:int'/> 
    <xs:element default='0' name='emergency' nillable='true' type='xs:int'/> 
    <xs:element default='0' name='idRoute' nillable='true' type='xs:int'/> 
    </xs:sequence> 
    </xs:complexType> 
    <xs:complexType name='MsjCor'> 
    <xs:sequence> 
    <xs:element name='last' type='xs:lng'/> 
    </xs:sequence> 
    </xs:complexType> 
    <xs:complexType name='InfoMoreCT'> 
    <xs:sequence> 
    <xs:element default='' name='CODDriver' nillable='true' type='xs:string'/> 
    </xs:sequence> 
    </xs:complexType> 
    <xs:complexType name='Result'> 
    <xs:sequence> 
    <xs:element name='result' type='xs:int'/> 
    <xs:element maxOccurs='unbounded' minOccurs='0' name='msjOPT' nillable='true' type='tns:Mesaje'/> 
    <xs:element name='msjcs' nillable='true' type='tns:MsjCor'/> 
    </xs:sequence> 
    </xs:complexType> 
    <xs:complexType name='Mesaje'> 
    <xs:sequence> 
    <xs:element name='type' type='xs:int'/> 
    <xs:element name='text' type='xs:string'/> 
    <xs:element name='date' type='xs:string'/> 
    <xs:element name='corr' type='xs:int'/> 
    </xs:sequence> 
    </xs:complexType> 
    </xs:schema> 
</types> 
<message name='Gator_Gator'> 
    <part element='tns:Gator' name='Gator'></part> 
</message> 
<message name='Gator_GatorResponse'> 
    <part element='tns:GatorResponse' name='GatorResponse'></part> 
</message> 
<message name='GatorFault'> 
    <part element='tns:GatorFault' name='GatorFault'></part> 
</message> 
<portType name='Gator'> 
    <operation name='Gator' parameterOrder='Gator'> 
    <input message='tns:Gator_Gator'></input> 
    <output message='tns:Gator_GatorResponse'></output> 
    <fault message='tns:GatorFault' name='GatorFault'></fault> 
    </operation> 
</portType> 
<binding name='GatorBinding' type='tns:Gator'> 
    <soap:binding style='document' transport='http://schemas.xmlsoap.org/soap/http'/> 
    <operation name='Gator'> 
    <soap:operation soapAction='http://home.com/gatorws/ws/Gator/Gator'/> 
    <input> 
    <soap:body use='literal'/> 
    </input> 
    <output> 
    <soap:body use='literal'/> 
    </output> 
    <fault name='GatorFault'> 
    <soap:fault name='GatorFault' use='literal'/> 
    </fault> 
    </operation> 
</binding> 
<service name='Gator'> 
    <port binding='tns:GatorBinding' name='GatorImplPort'> 
    <soap:address location='https://10.0.2.2:8080/gatoryws/Gator?wsdl'/> 
    </port> 
</service> 
</definitions> 

Я просто могу получить ответ об ошибке с веб-службы.

Я пробовал http://www.wsdl2code.com, но это для .NET webservices.

Я также пробовал http://easywsdl.com/, но я не понимаю, как это работает в моем случае.

Есть ли другой инструмент, который я мог бы использовать? Должен ли я перейти на Android Studio?

+0

Если вам интересно, если Android-студия поможет ваш веб-запрос полностью успешно, вы должны пойти читать на протокол, который вы пытаетесь использовать. http://www.w3schools.com/xml/xml_soap.asp – JakeWilson801

ответ

0

Я нашел, что это было действительно полезно: http://binarylifebyanjula.blogspot.cl/2013/11/android-webservices-ksoap2-complex.html

Здесь я собираюсь рассказать вам, как получить сложный объект типа. Для этого я создал ComplexTypeActivity. Для пользовательского интерфейса я просто добавил кнопку и текстовое представление для отображения результатов. Давайте создадим класс сложного типа. Здесь я создал класс, который содержит 3 строковых значения. Я назвал его как SimpleObject.

public class SimpleObject implements KvmSerializable { 

private String name; 
private String address; 
private String id; 

public String getId() { 
    return id; 
} 

public void setId(String id) { 
    this.id = id; 
} 

public String getName() { 
    return name; 
} 

public void setName(String name) { 
    this.name = name; 
} 

public String getAddress() { 
    return address; 
} 

public void setAddress(String address) { 
    this.address = address; 
} 

@Override 
public Object getProperty(int pid) { 
    // TODO Auto-generated method stub 
    switch (pid) { 
    case 0: 
    return this.id; 

    case 1: 
    return this.name; 

    case 2: 
    return this.address; 

    default: 
    break; 

    } 

    return null; 
} 

@Override 
public int getPropertyCount() { 
    // TODO Auto-generated method stub 
    return 3; 
} 

@Override 
public void getPropertyInfo(int index, Hashtable htable, PropertyInfo info)     { 
    // TODO Auto-generated method stub 

    switch (index) { 
    case 0: 
    info.type = PropertyInfo.STRING_CLASS; 
    info.name = "id"; 
    break; 
    case 1: 
    info.type = PropertyInfo.STRING_CLASS; 
    info.name = "name"; 
    break; 
    case 2: 
    info.type = PropertyInfo.STRING_CLASS; 
    info.name = "address"; 
    break; 

    } 

} 

@Override 
public void setProperty(int index, Object value) { 
    // TODO Auto-generated method stub 
    switch (index) { 
    case 0: 
    this.id = value.toString(); 
    break; 
    case 1: 
    this.name = value.toString(); 
    break; 
    case 2: 
    this.address = value.toString(); 
    break; 

    } 

} 

} 

Обратите внимание, что здесь я реализовал интерфейс KvmSerializable. Используя этот интерфейс, KSOAP сопоставляет эти свойства класса с мыльным сообщением.

Как и раньше, я нахожу вызов веб-службы при нажатии кнопки.

btnShowDetails.setOnClickListener(new OnClickListener() { 

    @Override 
    public void onClick(View v) { 
    LoadDetailsTask task = new LoadDetailsTask(); 
    task.execute("ID01"); 
} 
}); 


class LoadDetailsTask extends AsyncTask<string simpleobject="" void=""> { 

    private final String NAMESPACE = "http://service.blog.anjula.com/"; 
    private final String URL = "http://112.135.137.22:8080/BlogWebService/BlogWebService?WSDL"; 
    private final String SOAP_ACTION = "http://service.blog.anjula.com/getDetails"; 
    private final String METHOD_NAME = "getDetails"; 

    SimpleObject result = new SimpleObject(); 

    @Override 
    protected SimpleObject doInBackground(String... addId) { 

    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); 

    PropertyInfo idListPropety = new PropertyInfo(); 

    idListPropety.setName("id"); 
    idListPropety.setValue(addId[0]); 
    idListPropety.setType(addId[0].getClass()); 
    request.addProperty(idListPropety); 

    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
    SoapEnvelope.VER11); 

    // envelope.dotNet = true; 
    envelope.setOutputSoapObject(request); 

    envelope.addMapping(NAMESPACE, "SimpleObject", 
    new SimpleObject().getClass()); 

    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL); 

    try { 
    androidHttpTransport.debug = true; 
    androidHttpTransport.call(SOAP_ACTION, envelope); 
    SoapObject response = (SoapObject) envelope.getResponse(); 

    result.setId(response.getProperty("id").toString()); 
    result.setName(response.getProperty("name").toString()); 
    result.setAddress(response.getProperty("address").toString()); 

    return result; 

    } catch (IOException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
    } catch (XmlPullParserException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
    } 

    return null; 

    } 

    @Override 
    protected void onPostExecute(SimpleObject result) { 
    // TODO Auto-generated method stub 
    if (result != null) 
    textViewResult.setText("Id: " + result.getId() + "\nName: " 
     + result.getName() + "\nAddress: " 
     + result.getAddress()); 
    } 

} 

Здесь вы можете видеть, что я сопоставляю out, используя имена полей.

result.setId(response.getProperty("id").toString()); 
    result.setName(response.getProperty("name").toString()); 
    result.setAddress(response.getProperty("address").toString()); 

В URL-адресе я ввел свой IP-адрес, потому что я запустил службу на своем компьютере. Поэтому вы должны изменить этот IP-адрес на свой IP-адрес, если вы используете серверное приложение на своем компьютере. После нажатия кнопки программа вызовет этот метод.

public SimpleObject getDetails(String id){ 
     SimpleObject result = new SimpleObject();   
     result.setId(id); 
     result.setName("Anjula"); 
     result.setAddress("Kaduwela");   
     return result;   
    } 

Это все: D

Смежные вопросы