Vous êtes sur la page 1sur 25

Consumir WebService Creado en

PHP con J2ME


febrero 8, 2013
En esta ocasin vamos a elaborar una aplicacin mvil para consumir el
webservice que ya hemos creado en php, usaremos j2me para lograr esto y
nuestra interfaz tendr un aspecto como el siguiente:

Bien, comencemos a desarrollar la aplicacin, es de aclarar que estoy utilizando
netbeans 6.9.1 para la creacin de dicha aplicacin.
Inicialmente abrimos netbeans y seleccionamos la opcin proyecto nuevo en la
barra de men, se nos abrir una ventana como la siguiente:

All Seleccionamos la Categora Java ME y en proyecto escogemos Mobile
Application, presionamos el botn siguiente, luego aparecer la siguiente ventana:

En esta ventana escribimos el nombre del proyecto que ser:
consume_webservice_php y luego hacemos clic en siguiente, observaremos esta
otra interfaz:

Aqu marcamos la Casilla Midp-2.0 y volvemos a hacer clic en siguiente:

Presionamos el botn terminar, veremos que se nos carga una aplicacin simple
de la siguiente manera:

luego agregamos varios elementos al screen o pantalla principal de nuestra
aplicacin como lo son:
1 StringItem, 1 gauge, 3 textfield y 4 okcommand, como se observa en la ventana
a continuacin:

de esta manera tenemos nuestro diseo de la aplicacin listo, ahora hace falta
hacer uso de la librera que nos permitir implementar el protocolo soap en j2me,
nos referimos a ksoap y puede ser descargada desde aqu.
una vez descargada, la pegamos dentro de la carpeta src de nuestro proyecto,
podemos crear una nueva llamada lib y all alojarla, tal y como se ve en la imagen:

luego, debemos agregar la referencia de la librera al proyecto, para ello
presionamos clic derecho sobre el nombre del proyecto y en el men contextual
que aparece escogemos la opcin propiedades (ultima opcin)

Luego, en la siguiente ventana que aparece, seleccionamos la categora libreras y
recursos, y en la parte derecha presionamos el botn agregar jar/zip tal y como se
ve en la imagen:

una vez hecho esto, se abrir una nueva ventana desde donde podemos buscar la
librera ksoap dentro de la carpeta lib de src en nuestro proyecto como se a
continuacin:

presionamos el botn abrir y luego ok

Listo, ahora se puede apreciar (en la parte izquierda de la ventana) que se ha
agregado un nuevo paquete al proyecto que corresponde a la librera ksoap.

ahora si podemos pasar al cdigo, Presionamos la pestaa source y agregamos
los siguientes imports:
1
2
3
4
5
6
7
8
9
import org.ksoap2.SoapEnvelope;

import org.ksoap2.serialization.SoapObject;

import org.ksoap2.serialization.SoapSerializationEnvelope;

import org.ksoap2.transport.HttpTransport;

import org.xmlpull.v1.XmlPullParserException;
ahora agregamos las siguientes 2 variables como globales dentro de la clase
principal HelloMidlet:
1
2
private String url = "http://192.168.33.1/ejemplows/servicio_web.php"
String encontro="";
despus de esto procedemos a programar en cada uno de los okcommand,
comencemos con okCommand_conexion, pero antes creemos la funcin
probar_conexion_ws() que ser invocada por este botn, el cdigo de dicha
funcin es:
1
2
3
4
5
6
7
8
9
10
//creo la funcion para probar la conexion con el webservice

public void probar_conexion_ws() throws Exception {

StringBuffer stringBuffer = new StringBuffer();

String valor_mensaje,mensaje_m;

valor_mensaje="";

System.out.println("entro 1");
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60

// add service call

String method = "enviar_respuesta";

SoapObject client = new SoapObject(url, method);

System.out.println("entro 2");

client.addProperty("parametro", "Funciona");

HttpTransport transport = new HttpTransport(url);

System.out.println("entro 3");

// creating the Soap Envelope

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

envelope.bodyOut = client;

System.out.println("entro 4");

// call the WebService

try {

transport.call(method, envelope);

System.out.println("entro 5");

} catch(XmlPullParserException io) {

System.err.println(io);

}

System.out.println("entro 6");

// format the Result

String result = envelope.getResponse().toString();

stringBuffer.append(result);

valor_mensaje=stringBuffer.toString();

this.stringItem_prueba.setText(valor_mensaje);

this.gauge.setValue(100);

}
61
62
63
ahora si podemos llamar la funcin desde nuestro okcommand para ello
presionamos click derecho sobre el okcommand_conexion (de la pantalla principal)
y en el men contextual que aparece seleccionamos la opcin go to source, como
se ve en la imagen:

luego en la seccin de cdigo a la que nos lleva escribiremos el llamado a la
funcin probar_conexion_ws() de la siguiente manera:
1
2
3
4
5
6
7
8
9
10
11
try {

probar_conexion_ws();

System.out.println("entro a correr si");

} catch (Exception ex) {

System.out.println("hola jacen "+ex);

}
de la misma manera programamos el botn u okcommand_nuevo, el cual se
encargara de borrar el texto que haya en los text:
1
2
3
4
//aqui va el codigo para el boton nuevo, lo que hago es que borro los text
this.textField_cedula.setString("");
this.textField_nombre.setString("");
this.textField_apellidos.setString("");
Pasemos ahora al okcommand_guardar, pero primero vamos a crear la funcin
guardar_datos() a continuacin:
1
2
3
//......creo una funcion para guardar los datos.........
public void guardar_datos() throws Exception {

4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
StringBuffer stringBuffer = new StringBuffer();

String valor_mensaje,mensaje_m;

valor_mensaje="";

System.out.println("entro 1");

// add service call

String method = "registrar_datos";

SoapObject client = new SoapObject(url, method);

System.out.println("entro 2");

client.addProperty("parametro",this.textField_cedula.getString());

client.addProperty("parametro2",this.textField_nombre.getString());

client.addProperty("parametro3",this.textField_apellidos.getString());

HttpTransport transport = new HttpTransport(url);

System.out.println("entro 3");

// creating the Soap Envelope

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

envelope.bodyOut = client;

System.out.println("entro 4");

// call the WebService

try {

transport.call(method, envelope);

System.out.println("entro 5");

} catch(XmlPullParserException io) {

System.err.println(io);

}

System.out.println("entro 6");

// format the Result

String result = envelope.getResponse().toString();

stringBuffer.append(result);
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76

valor_mensaje=stringBuffer.toString();

this.stringItem_prueba.setText("");

if(valor_mensaje.equals("Si")){

this.stringItem_prueba.setText("Datos Guardados correctamente!");

}

else{

this.stringItem_prueba.setText("No Fue Posible Guardar!");

}

}
Bien, despus de esto si podemos hacer el llamado a la funcin guardar_datos()
dentro de la seccin de cdigo del okcommand_guardar asi:
1
2
3
4
5
6
7
8
9
10
11
//aqui va el codigo para el boton guardar datos
try {

guardar_datos();

System.out.println("entro a correr si");

} catch (Exception ex) {

System.out.println("hola jacen "+ex);
}
Por ultimo solo nos hace falta programar el okcommand_buscar, pero como hemos
hecho en las dems opciones, aqu tambin vamos a crear una funcin llamada
buscar_datos() que se encargara de verificar si la persona a buscar por la cedula
se encuentra o no registrado en la base de datos.
este es el cdigo:
1
2
3
4
5
6
7
//creo una funcion para buscar los datos
public void buscar_datos() throws Exception {

StringBuffer stringBuffer = new StringBuffer();

String valor_mensaje,mensaje_m;

valor_mensaje="";
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57

System.out.println("entro 1");

// add service call

String method = "buscar_datos";

SoapObject client = new SoapObject(url, method);

System.out.println("entro 2");

client.addProperty("cedula",this.textField_cedula.getString());

HttpTransport transport = new HttpTransport(url);

System.out.println("entro 3");

// creating the Soap Envelope

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

envelope.bodyOut = client;

System.out.println("entro 4");

// call the WebService

try {

transport.call(method, envelope);

System.out.println("entro 5");

} catch(XmlPullParserException io) {

System.err.println(io);

}

System.out.println("entro 6");

// format the Result

String result = envelope.getResponse().toString();

stringBuffer.append(result);

valor_mensaje=stringBuffer.toString();

encontro=valor_mensaje;

}
58
59
60
Bien, como es de notarse, la funcin buscar_datos() solo nos permite verificar si
una persona existe o no en la base de datos, sin embargo si deseamos mostrar los
datos de una persona asociados a la cedula y que se encuentra en la base de
datos, deberemos implementar las siguientes
funciones mostrar_cedula(),mostrar_nombre(), mostrar_apellidos() una para
cada campo del registro existente en la base de datos, a continuacin
desarrollaremos cada una de ellas:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
//........comienzo procedimiento para mostrar los datos...........

//procedimiento para mostrar la cedula de la base de datos

public void mostrar_cedula() throws Exception {

StringBuffer stringBuffer = new StringBuffer();

String valor_mensaje,mensaje_m;

valor_mensaje="";

System.out.println("entro 1");

// add service call

String method = "mostrar_datos_cedula";

SoapObject client = new SoapObject(url, method);

System.out.println("entro 2");

client.addProperty("cedula",this.textField_cedula.getString());

HttpTransport transport = new HttpTransport(url);

System.out.println("entro 3");

// creating the Soap Envelope

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

envelope.bodyOut = client;

System.out.println("entro 4");

// call the WebService

try {

transport.call(method, envelope);

39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
System.out.println("entro 5");

} catch(XmlPullParserException io) {

System.err.println(io);

}

System.out.println("entro 6");

// format the Result

String result = envelope.getResponse().toString();

stringBuffer.append(result);

valor_mensaje=stringBuffer.toString();

this.textField_cedula.setString(valor_mensaje);

}

//mostrar datos....nombre..................

public void mostrar_nombre() throws Exception {

StringBuffer stringBuffer = new StringBuffer();

String valor_mensaje,mensaje_m;

valor_mensaje="";

System.out.println("entro 1");

// add service call

String method = "mostrar_datos_nombre";

SoapObject client = new SoapObject(url, method);

System.out.println("entro 2");

client.addProperty("cedula",this.textField_cedula.getString());

HttpTransport transport = new HttpTransport(url);

System.out.println("entro 3");

// creating the Soap Envelope

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

envelope.bodyOut = client;

System.out.println("entro 4");
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138

// call the WebService

try {

transport.call(method, envelope);

System.out.println("entro 5");

} catch(XmlPullParserException io) {

System.err.println(io);

}

System.out.println("entro 6");

// format the Result

String result = envelope.getResponse().toString();

stringBuffer.append(result);

valor_mensaje=stringBuffer.toString();

this.textField_nombre.setString(valor_mensaje);

}

//mostrar_datos....apellidos............................

public void mostrar_apellidos() throws Exception {

StringBuffer stringBuffer = new StringBuffer();

String valor_mensaje,mensaje_m;

valor_mensaje="";

System.out.println("entro 1");

// add service call

String method = "mostrar_datos_apellido";

SoapObject client = new SoapObject(url, method);

System.out.println("entro 2");

client.addProperty("cedula",this.textField_cedula.getString());

HttpTransport transport = new HttpTransport(url);

System.out.println("entro 3");

139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
// creating the Soap Envelope

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

envelope.bodyOut = client;

System.out.println("entro 4");

// call the WebService

try {

transport.call(method, envelope);

System.out.println("entro 5");

} catch(XmlPullParserException io) {

System.err.println(io);

}

System.out.println("entro 6");

// format the Result

String result = envelope.getResponse().toString();

stringBuffer.append(result);

valor_mensaje=stringBuffer.toString();

this.textField_apellidos.setString(valor_mensaje);

}
Despus de todo esto, con el procedimiento de bsqueda y muestra de datos
listos, podemos hacer el llamado de estas funciones dentro de la seccin de
cdigo del okcommand_buscar de la siguiente manera:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
//aqui va el codigo para la funcion buscar datos
try {

encontro="No";

buscar_datos();

if(encontro.equals("Si")){

//muestro los datos teniendo en cuenta cada una de las funciones creadas

this.stringItem_prueba.setText("");

mostrar_cedula();

mostrar_nombre();

mostrar_apellidos();

}

else{

this.textField_cedula.setString("");

this.textField_nombre.setString("");

this.textField_apellidos.setString("");

this.stringItem_prueba.setText("");

this.stringItem_prueba.setText("Usuario no Encontrado en la Base de datos");

}

System.out.println("entro a correr si");

} catch (Exception ex) {

System.out.println("hola jacen "+ex);

}
Bien de esta manera hemos terminado en lo que a programacin respecta de
nuestra aplicacin, ahora podemos hacerle pruebas.
Una vez ejecutada esta, escogemos la opcin men y all seleccionamos la opcin
probar conexin.
Si estamos en la misma red en la que se encuentra alojado el servicio web la
conexin ser exitosa, veremos un mensaje de notificacin en la parte superior y el
control gauge se llenara como en la siguiente imagen:

Luego podemos proceder a registrar algunos datos, para ello primero ingresamos
los datos respectivos y escogemos del men la opcin Guardar Datos

si el proceso es efectuado correctamente veremos un mensaje en la parte superior
indicando lo ocurrido:

Bueno, hemos verificado que la aplicacin funciona correctamente, si desean
probar en un celular solo hay que presionar clic derecho sobre el nombre del
proyecto en netbeans y en el men contextual que aparece, escoger la opcin
clean & build para que se genere el archivo jar.

Luego, nos dirigimos a la carpeta dist del proyecto (en el directorio de programas
de netbeans) y transferimos al telfono mvil el archivo llamado
consume_webservice_php.jar.

Posteriormente procedemos a instalarlo y si las configuraciones de red son
correctas se observara a la aplicacin funcionando como debe ser.
Eso es todo amigos, espero y esta aplicacin les sea de utilidad, si deseas
descargar la aplicacin, mas adelante esta el enlace.
Descargar Aplicacin

Vous aimerez peut-être aussi