Hüseyin Çelik Blog Sayfasi

.Net, Java, Android, Progress 4gl Paylasimlarim

Androidde web servis kullanimi

Bir süredir yazmayi planladigim web servis kullanimini anlatacagim. Öncelikle androidden webservise baglanmak için projenize ksoap2-android-assembly-2.6.0-jar-with-dependencies.jar isimli kütüphaneyi eklemelisiniz. Bir web servis yazalim. Iste basit bir web servis örnegi:

[WebMethod(EnableSession = false)]
public TestResultObject TestMethod(TestParamObject paramObject)
{
    var resp = new TestResultObject();

    resp.Sonuc = true;
    resp.Mesaj = "Web servis mesaji.";

    return resp;
}

public class TestParamObject
{
    public int Id { get; set; }
    public string Kod { get; set; }
    public List<string> StrList { get; set; } 
}

public class TestResultObject
{
    public bool Sonuc { get; set; }
    public string Mesaj { get; set; }
}

Simdide web servisi çalistiralim ve WSDL olarak inceleyelim. Sonra android için objelerimizi hazirlayalim. Öncelikle tüm objelerimizin türetilecegi base objecti yazalim.

public abstract class BaseObject implements KvmSerializable, Serializable {

    protected static final String NAMESPACE = "http://tempuri.org/";

    public BaseObject()
    {
        super();
    }

}

Marshal classlarini yazalim. Bu classlar web servis içinde decimal double kullanilirsa gerekiyor.

public class MarshalDecimal implements Marshal {

	@Override
	public Object readInstance(XmlPullParser parser, String namespace, String name, PropertyInfo expected) throws IOException, XmlPullParserException {
		return BigDecimal.valueOf(Double.parseDouble(parser.nextText()));
	}


	@Override
	public void register(SoapSerializationEnvelope cm) {
		cm.addMapping(cm.xsd, "decimal", BigDecimal.class, this);
	}


	@Override
	public void writeInstance(XmlSerializer writer, Object obj) throws IOException {
		writer.text(obj.toString());		
	}
	
	public static double round(double d, int decimalPlace) {

		BigDecimal bd = new BigDecimal(Double.toString(d));
		bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);
		return bd.doubleValue();
	}
	
}
public class MarshalDouble implements Marshal {

	@Override
	public Object readInstance(XmlPullParser parser, String namespace, String name, PropertyInfo expected) throws IOException, XmlPullParserException {
		return Double.parseDouble(parser.nextText());
	}


	@Override
	public void register(SoapSerializationEnvelope cm) {
		cm.addMapping(cm.xsd, "double", Double.class, this);
	}


	@Override
	public void writeInstance(XmlSerializer writer, Object obj) throws IOException {
		writer.text(obj.toString());		
	}
	
}
public class MarshalFloat implements Marshal {

	@Override
	public Object readInstance(XmlPullParser parser, String namespace, String name, PropertyInfo expected) throws IOException, XmlPullParserException {
		return Float.parseFloat(parser.nextText());
	}


	@Override
	public void register(SoapSerializationEnvelope cm) {
		cm.addMapping(cm.xsd, "double", Float.class, this);
	}


	@Override
	public void writeInstance(XmlSerializer writer, Object obj) throws IOException {
		writer.text(obj.toString());		
	}
	
}
public class MarshalDate implements Marshal {
	
	public static Class DATE_CLASS = new Date(0).getClass();

	@Override
	public Object readInstance(XmlPullParser parser, String namespace, String name, PropertyInfo expected) throws IOException, XmlPullParserException{
			//IsoDate.DATE_TIME=3
			String Test1 = parser.nextText();
			return IsoDate.stringToDate(parser.nextText(), IsoDate.DATE_TIME);
	}

	@Override
	public void register(SoapSerializationEnvelope cm) {
		cm.addMapping(cm.xsd, "dateTime", MarshalDate.DATE_CLASS, this);
		// "DateTime" is wrong use "dateTime" ok
		
	}

	@Override
	public void writeInstance(XmlSerializer writer, Object obj) throws IOException{
			String Test="";
			Test = IsoDate.dateToString((Date) obj, IsoDate.DATE_TIME);
			writer.text(IsoDate.dateToString((Date) obj, IsoDate.DATE_TIME));
	}

}

Parametre objesi

public class TestParamObject extends BaseObject {

     public Integer Id = 0;
     public String Kod = "";
     public ArrayOfString StrList = new ArrayOfString();  //array


    public Object getProperty(int index)
    {
    	switch (index)
    	{
           case 0: 
                return Id; 
           case 1: 
                return Kod; 
           case 2: 
                return StrList; 

    	}

    	return null;
    }

    public int getPropertyCount()
    {
        return 3;
    }

    @SuppressWarnings("unchecked")
    public void getPropertyInfo(int index, Hashtable properties, PropertyInfo info) {
    	//info.type = PropertyInfo.STRING_CLASS;
    	switch (index) {

           case 0: 
                info.name = "Id"; 
                info.type = PropertyInfo.INTEGER_CLASS; 
                             break; 
           case 1: 
                info.name = "Kod"; 
                info.type = PropertyInfo.STRING_CLASS; 
                             break; 
           case 2: 
                info.name = "StrList"; 
                info.type = new ArrayOfString().getClass(); 
                             break; 

        default:
            break;
        }
    }

    public void setProperty(int index, Object value)
    {
    	switch (index)
    	{
           case 0: 
            if(value.toString().equalsIgnoreCase("anyType{}"))
                  Id = 0;
            else 
	                Id = Integer.parseInt(value.toString()); 
                  break; 
           case 1: 
            if(value.toString().equalsIgnoreCase("anyType{}"))
                  Kod = "";
            else 
	                Kod = value.toString(); 
                  break; 
           case 2: 
              if(value != null){ 
                  StrList = new ArrayOfString(); 
                  SoapObject prp = (SoapObject)value; 
                  int itemCount = prp.getPropertyCount(); 
                  for(int loop=0;loop<itemCount;loop++){ 
                  if(prp.getProperty(loop) instanceof SoapObject){ 
                  SoapObject pi = (SoapObject)prp.getProperty(loop); 
                      String item = new String(); 
                      item = pi.getProperty(0).toString();
                  StrList.add(item); 
                   } 
                  	  if(prp.getProperty(loop) instanceof SoapPrimitive){ 
                  	  SoapPrimitive pi = (SoapPrimitive)prp.getProperty(loop); 
                  	  String item = pi.toString(); 
                   	  StrList.add((String)item); 
                    } 
                   } 
                  } 
                  break; 

    	}

    }
    
	public void loadSoapObject(SoapObject property){
		if(property == null) return;
		int pr = getPropertyCount();
		PropertyInfo pro = new PropertyInfo();
		for(int i=0;i<pr;i++){
			getPropertyInfo(i, null, pro);
			if(property.hasProperty(pro.name))
				setProperty(i, property.getProperty(pro.name));
		}
	}     

}

Array objesi

public class ArrayOfString extends Vector<String> implements KvmSerializable {

    private static final long serialVersionUID = 1L;
    String n1 = "http://tempuri.org/";

    protected String getItemDescriptor()
    {
        return "string";
    }

    // This describes what type of objects are to be contained in the Array
    protected Class getElementClass() {
        return String.class.getClass();
    }

    /// by TORO
    @Override
    public Object getProperty(int arg0) {
        return this.get(arg0);
    }

    @Override
    public int getPropertyCount() {
        return this.size();
    }

    @Override
    public void getPropertyInfo(int arg0, Hashtable arg1, PropertyInfo arg2) {
        arg2.name = "string";
        arg2.type = String.class.getClass();
        arg2.namespace = n1;
    }

    @Override
    public void setProperty(int arg0, Object arg1) {
        this.add((String)arg1);
    }
    
	public void loadSoapObject(SoapObject property){
		if(property == null) return;
		int itemCount = property.getPropertyCount();
		if(itemCount > 0){
			for(int loop=0;loop < itemCount;loop++){
				SoapObject pii = (SoapObject)property.getProperty(loop);
				String item = new String();
				item = pii.getProperty(0).toString();
				this.add(item);
        	}
        }
	}    

}

Dönüs objesi

public class TestMethodResponse extends BaseObject {

    public TestResultObject TestMethodResult;


    public Object getProperty(int index)
    {

    	return TestMethodResult;

    }

    public int getPropertyCount()
    {
        return 1;
    }

    @SuppressWarnings("unchecked")
	public void getPropertyInfo(int index, Hashtable properties, PropertyInfo info)
    {

    	info.name = "TestMethodResult";
        info.type = PropertyInfo.STRING_CLASS;

    }

    public void setProperty(int index, Object value)
    {

    	TestMethodResult = (TestResultObject)value;

    }
    
	public void loadSoapObject(SoapObject property){
		if(property == null) return;
		TestMethodResult = new TestResultObject();
		TestMethodResult.loadSoapObject(property);
	}           
}
public class TestResultObject extends BaseObject {

     public Boolean Sonuc = false;
     public String Mesaj = "";


    public Object getProperty(int index)
    {
    	switch (index)
    	{
           case 0: 
                return Sonuc; 
           case 1: 
                return Mesaj; 

    	}

    	return null;
    }

    public int getPropertyCount()
    {
        return 2;
    }

    @SuppressWarnings("unchecked")
    public void getPropertyInfo(int index, Hashtable properties, PropertyInfo info) {
    	//info.type = PropertyInfo.STRING_CLASS;
    	switch (index) {

           case 0: 
                info.name = "Sonuc"; 
                info.type = PropertyInfo.BOOLEAN_CLASS; 
                             break; 
           case 1: 
                info.name = "Mesaj"; 
                info.type = PropertyInfo.STRING_CLASS; 
                             break; 

        default:
            break;
        }
    }

    public void setProperty(int index, Object value)
    {
    	switch (index)
    	{
           case 0: 
            if(value.toString().equalsIgnoreCase("anyType{}"))
                  Sonuc = false;
            else 
	                Sonuc = Boolean.parseBoolean(value.toString()); 
                  break; 
           case 1: 
            if(value.toString().equalsIgnoreCase("anyType{}"))
                  Mesaj = "";
            else 
	                Mesaj = value.toString(); 
                  break; 

    	}

    }
    
	public void loadSoapObject(SoapObject property){
		if(property == null) return;
		int pr = getPropertyCount();
		PropertyInfo pro = new PropertyInfo();
		for(int i=0;i<pr;i++){
			getPropertyInfo(i, null, pro);
			if(property.hasProperty(pro.name))
				setProperty(i, property.getProperty(pro.name));
		}
	}     

}

Metod objesi

public class TestMethod extends BaseObject {

    private static final String METHOD_NAME = "TestMethod";
    private static final String NAMESPACE = "http://tempuri.org/";

     public TestParamObject paramObject = new TestParamObject();


	public SoapObject GetSoapParams()
	{
         SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);         
		PropertyInfo p0 = new PropertyInfo();
		p0.setName("paramObject");
		p0.setValue(paramObject);
		p0.setType(paramObject.getClass());
		p0.setNamespace(NAMESPACE);
		request.addProperty(p0);



         return request;
	}

	public String GetSoapAction()
	{
		return NAMESPACE + METHOD_NAME;
	}
	
    public Object getProperty(int index)
    {
    	switch (index)
    	{
           case 0: 
                return paramObject; 

    	}

    	return null;
    }
    
    public int getPropertyCount()
    {
        return 2;
    }

    @SuppressWarnings("unchecked")
    public void getPropertyInfo(int index, Hashtable properties, PropertyInfo info) {
    	//info.type = PropertyInfo.STRING_CLASS;
    	switch (index) {

           case 0: 
                info.name = "paramObject"; 
                info.type = new TestParamObject().getClass(); 
                             break; 

        default:
            break;
        }
    }
    
    public void setProperty(int index, Object value)
    {
    	switch (index)
    	{
           case 0: 
                paramObject = (TestParamObject)value; 
                  break; 

    	}

    }
    
	public void loadSoapObject(SoapObject property){
		if(property == null) return;
		int pr = getPropertyCount();
		PropertyInfo pro = new PropertyInfo();
		for(int i=0;i<pr;i++){
			getPropertyInfo(i, null, pro);
			if(property.hasProperty(pro.name))
				setProperty(i, property.getProperty(pro.name));
		}
	}         	

}

Ve son olarak soap class

public final class testSoap
	{

		private Boolean debug = true;
		private String requestDump = "";
		private String responseDump = "";
		private String faultstring = "";

		public String Address;
		public boolean IsDotNet = true;
		public int TimeOut = 100000;
		protected static final String NAMESPACE = "http://tempuri.org/";

	public TestMethodResponse TestMethod(TestMethod params) throws Exception
		{
		
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			envelope.dotNet = IsDotNet;
			envelope.setOutputSoapObject(params.GetSoapParams());
	    
			envelope.addMapping(NAMESPACE, "TestMethod", TestMethod.class);
			envelope.addMapping(NAMESPACE, "TestParamObject", TestParamObject.class);
			envelope.addMapping(NAMESPACE, "ArrayOfString", ArrayOfString.class);

			new MarshalDecimal().register(envelope);
			new MarshalDouble().register(envelope);
			new MarshalDate().register(envelope);
			new MarshalFloat().register(envelope);
	    			

			HttpTransportSE androidHttpTransport = new HttpTransportSE(Address, TimeOut);
			androidHttpTransport.debug = debug;
			
			try{
				androidHttpTransport.call(params.GetSoapAction(), envelope);
			}
			catch (SocketTimeoutException s) {
				faultstring = s.getMessage();
				s.printStackTrace();
				Log.e(getClass().getSimpleName() + "/TestMethod", faultstring);
				return null;
			}
			catch (IOException n) {
				faultstring = n.getMessage();
				n.printStackTrace();
				Log.e(getClass().getSimpleName() + "/TestMethod", faultstring);
				return null;
			}
			catch (Exception e) {
				faultstring = e.getMessage();
				e.printStackTrace();
				Log.e(getClass().getSimpleName() + "/TestMethod", e.getMessage());
				return null;
			}
			
			if(debug == true){
				requestDump = androidHttpTransport.requestDump;
				responseDump = androidHttpTransport.responseDump;
			}
	        
			TestMethodResponse resp = null;
			SoapFault fault = getFault(envelope);
			if(fault == null){
        		//resp = TestMethodResponse.class.cast(envelope.bodyIn);
        		SoapObject response = (SoapObject)envelope.getResponse();
        		if(response != null){
        			resp = new TestMethodResponse();
        			resp.loadSoapObject(response);
        		}        		
			}
			else{
				Log.i(getClass().getSimpleName(), fault.faultstring);
        		throw new Exception(fault.faultstring);
			}

			return resp;
	       
		}

	
	public String getRequestDump(){
		return requestDump;
	}
	
	public String getResponseDump(){
		return responseDump;
	}
	
	public String getFaultString(){
		return faultstring;
	}

	public void setDebug(Boolean isdebug){
		debug = isdebug;
	}		

	private SoapFault getFault(SoapSerializationEnvelope envelope){
		SoapFault fault = null;
		faultstring = "";
		try{
			fault = SoapFault.class.cast(envelope.bodyIn);
			Log.e(getClass().getSimpleName(), fault.faultstring);
			faultstring = fault.faultstring;
		}
		catch ( final ClassCastException ex ){
			ex.printStackTrace();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return fault;
	}

	}

testSoap classini kullanarak web servisi çagirabiliyoruz. Yardim ve destek için iletisime geçin. Burda dikkat etmeniz gereken kisim setProperty ve getProperty içinde indexe dikkat edilmelidir.

Web servisi yazdiniz ve obje içinde bir degisiklik yapmaniz gerekirse objedeki setproperty ve getproperty indexlerinin yeniden düzenlenmesi gerekiyor. Ben bunu yapmak için program yazdim ve program kullaniyorum. Bütün bu classlari bu programa yazdiriyorum :-).

android wsdl parser

Loading