Visualizzazione dei risultati da 1 a 3 su 3
  1. #1
    Utente di HTML.it L'avatar di pcg4m3s
    Registrato dal
    Aug 2007
    Messaggi
    244

    WebService SOAP Android

    Salve,
    ho creato un semplice webservice che fa la somma di due numeri e un'app di prova su android che utilizza il webservice.

    Il codice del webservice è il seguente:

    INTERFACCIA:
    codice:
    package com.example;
    
    import javax.jws.WebService;
    
    @WebService
    public interface Somma {
    	public int returnSomma(int a, int b);
    }
    CLASSE JAVA:
    codice:
    package com.example;
    
    import javax.jws.WebService;
    
    @WebService
    public class SommaImpl implements Somma {
    
    	public int returnSomma(int a, int b)
    	{
    		return a+b;
    	}
    }
    Ho deployato il webservice su jboss e il wsdl ottenuto è il seguente:
    codice:
    <wsdl:definitions name="SommaImplService" targetNamespace="http://example.com/" xmlns:ns1="http://schemas.xmlsoap.org/soap/http" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://example.com/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <wsdl:types>
    <xs:schema elementFormDefault="unqualified" targetNamespace="http://example.com/" version="1.0" xmlns:tns="http://example.com/" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="returnSomma" type="tns:returnSomma"/>
    <xs:element name="returnSommaResponse" type="tns:returnSommaResponse"/>
    <xs:complexType name="returnSomma">
        <xs:sequence>
          <xs:element name="arg0" type="xs:int"/>
          <xs:element name="arg1" type="xs:int"/>
        </xs:sequence>
      </xs:complexType>
    <xs:complexType name="returnSommaResponse">
        <xs:sequence>
          <xs:element name="return" type="xs:int"/>
        </xs:sequence>
      </xs:complexType>
    </xs:schema>
      </wsdl:types>
      <wsdl:message name="returnSomma">
        <wsdl:part element="tns:returnSomma" name="parameters">
        </wsdl:part>
      </wsdl:message>
      <wsdl:message name="returnSommaResponse">
        <wsdl:part element="tns:returnSommaResponse" name="parameters">
        </wsdl:part>
      </wsdl:message>
      <wsdl:portType name="Somma">
        <wsdl:operation name="returnSomma">
          <wsdl:input message="tns:returnSomma" name="returnSomma">
        </wsdl:input>
          <wsdl:output message="tns:returnSommaResponse" name="returnSommaResponse">
        </wsdl:output>
        </wsdl:operation>
      </wsdl:portType>
      <wsdl:binding name="SommaImplServiceSoapBinding" type="tns:Somma">
        <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
        <wsdl:operation name="returnSomma">
          <soap:operation soapAction="" style="document"/>
          <wsdl:input name="returnSomma">
            <soap:body use="literal"/>
          </wsdl:input>
          <wsdl:output name="returnSommaResponse">
            <soap:body use="literal"/>
          </wsdl:output>
        </wsdl:operation>
      </wsdl:binding>
      <wsdl:service name="SommaImplService">
        <wsdl:port binding="tns:SommaImplServiceSoapBinding" name="SommaImplPort">
          <soap:address location="http://RC530:8080/SommaWS-Maven/SommaImpl"/>
        </wsdl:port>
      </wsdl:service>
    </wsdl:definitions>
    Infine ho creato la seguente activity per android che permette di inserire due numeri ed eseguire la somma richiamando il webservice:
    codice:
    package com.example;
    
    import org.ksoap2.SoapEnvelope;
    import org.ksoap2.SoapFault;
    import org.ksoap2.serialization.SoapObject;
    import org.ksoap2.serialization.SoapSerializationEnvelope;
    import org.ksoap2.transport.HttpTransportSE;
    import android.os.Bundle;
    import android.app.Activity;
    import android.content.Intent;
    import android.view.Menu;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    
    public class MainActivity extends Activity {
    	private static String NAMESPACE = "http://example.com/";
    	private static String METHOD_NAME = "returnSomma";
    	private static String SOAP_ACTION = "";
    	private static String URL = "http://192.168.1.68:8080/SommaWS-Maven/SommaImpl?wsdl";
    	EditText editTextnumero1, editTextnumero2;
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);
    
    		editTextnumero1=(EditText)findViewById(R.id.editTextNumero1);
    		editTextnumero2=(EditText)findViewById(R.id.editTextNumero2);
    		
    		Button buttonSomma=(Button)findViewById(R.id.buttonSomma);
    
    		buttonSomma.setOnClickListener(new OnClickListener() {
    			@Override
    			public void onClick(View v) {
    				// TODO Auto-generated method stub
    				chiamaWebServiceSomma();
    			}
    		});
    	}
    	
    	@Override
    	public boolean onCreateOptionsMenu(Menu menu) {
    		// Inflate the menu; this adds items to the action bar if it is present.
    		getMenuInflater().inflate(R.menu.main, menu);
    		return true;
    	}
    
    	public void chiamaWebServiceSomma()
    	{
    		int numero1=Integer.parseInt(editTextnumero1.getText().toString());
    		int numero2=Integer.parseInt(editTextnumero2.getText().toString());
    		TextView textViewRisultato=(TextView)findViewById(R.id.textViewRisultato);
    				
    		SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);  
    		request.addProperty("arg0", numero1);
    		request.addProperty("arg1", numero2);
    
    		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    		envelope.setOutputSoapObject(request);
    		envelope.dotNet = true;
    		try {
    			HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
    			
    			//this is the actual part that will call the webservice
    			androidHttpTransport.call(SOAP_ACTION, envelope);
    
    			//Get the SoapFault from the envelope body.
    			SoapFault error = (SoapFault)envelope.bodyIn;
    			System.out.println("Error message : "+error.toString());
    			
    			//Get the SoapResult from the envelope body.
    			SoapObject result = (SoapObject)envelope.bodyIn;
    
    			if(result != null)
    				//Get the first property and change the label text
    				textViewRisultato.setText(result.getProperty(0).toString());
    			else
    				textViewRisultato.setText("Nessun risultato");
    		} catch (Exception e) {
    			textViewRisultato.setText("Eccezione!");
    			e.printStackTrace();
    		}
    	}
    }
    Il problema è che quando avvio l'app ho il seguente messaggio di errore:
    codice:
    Error message : SoapFault - faultcode: 'soap:Client' faultstring: 'Unmarshalling Error: unexpected element (uri:"http://example.com/", local:"arg0"). Expected elements are <{}arg1>,<{}arg0> ' faultactor: 'null' detail: null
    codice:
    java.lang.ClassCastException: org.ksoap2.SoapFault cannot be cast to org.ksoap2.serialization.SoapObject
    at com.example.MainActivity.chiamaWebServiceSomma(MainActivity.java:94)
    at com.example.MainActivity$1.onClick(MainActivity.java:43)
    at android.view.View.performClick(View.java:4211)
    at android.view.View$PerformClick.run(View.java:17267)
    at android.os.Handler.handleCallback(Handler.java:615)
    at android.os.Handler.dispatchMessage(Handler.java:92)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:4898)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
    at dalvik.system.NativeStart.main(Native Method)

  2. #2
    Utente di HTML.it L'avatar di andbin
    Registrato dal
    Jan 2006
    residenza
    Italy
    Messaggi
    18,284

    Re: WebService SOAP Android

    Originariamente inviato da pcg4m3s
    Il problema è che quando avvio l'app ho il seguente messaggio di errore:
    codice:
    java.lang.ClassCastException: org.ksoap2.SoapFault cannot be cast to org.ksoap2.serialization.SoapObject
    Premessa: non conosco questa libreria ksoap2 e ne so relativamente poco su SOAP. Però qualche indicazione posso dartela lo stesso.

    Innanzitutto l'eccezione mi pare ben chiara: tu stai cercando di "vedere" come SoapObject un oggetto che invece è realmente tutta un'altra cosa, ovvero un SoapFault. Chiaramente non va bene.

    Tieni presente che il "fault" di SOAP è nel body della response ma non sempre ... solo se c'è un errore appunto. Quindi dovresti come minimo fare qualche controllo e non fare cast deliberati come hai fatto.

    Per curiosità, sono andato a vedere il javadoc della ksoap2: la classe SoapSerializationEnvelope ha un metodo:

    public java.lang.Object getResponse() throws SoapFault

    Se ha successo, hai il tuo oggetto (quello che devi gestire lo saprai tu), altrimenti lancia un SoapFault e a quel punto puoi catturarlo/gestirlo come credi. Insomma è un approccio migliore e più sensato.

    Naturalmente non so altro e non so dirti se c'è una strada migliore.
    Andrea, andbin.devSenior Java developerSCJP 5 (91%) • SCWCD 5 (94%)
    java.util.function Interfaces Cheat SheetJava Versions Cheat Sheet

  3. #3
    direi che ti conviene provare il WS su un PC, poi quando funzionerà lo trasporti sopra mobile...ovviamente devi costruirti un piccolo client per le richieste SOAP.
    Controlla la risposta con applicativi sniffer tipo fiddler e vedi la risposta che ti ritorna il WS...
    I computer sono incredibilmente veloci, accurati e stupidi.
    Gli uomini sono incredibilmente lenti, inaccurati e intelligenti.
    Insieme sono una potenza che supera l'immaginazione.

    A.Einstein

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.