Está en la página 1de 7

TALLER WEB SERVICES JAVA-ANDROI

1. Instale jsdk y netbeans 7.4


2. Abra Netbeans y cree un proyecto Web llamado CalculadoraWeb.
3. Cree un nuevo arhcivo de Tipo Web Services llamado calcservices.

4. De click derecho sobre el web services creado y selecciones Add


Operation, debe crear tres operaciones suma, resta y multiplicar. Cada
Operacin debe retornar un tipo entero y tener dos parmetros (valor1 y
valor2) de tipo entero.

El archivo que se crear debe tener el siguiente cdigo:

package services;

import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;

/**
*
* @author framos
*/
@WebService(serviceName = "calcservices")
public class calcservices {

/**
* This is a sample web service operation
*/
@WebMethod(operationName = "hello")
public String hello(@WebParam(name = "name") String txt) {
return "Hello " + txt + " !";
}

/**
* Web service operation
*/
@WebMethod(operationName = "suma")
public int suma(@WebParam(name = "valor1") int valor1, @WebParam(name
= "valor2") int valor2) {
//TODO write your implementation code here:
return (valor1+valor2);
}

/**
* Web service operation
*/
@WebMethod(operationName = "multiplicar")
public int multiplicar(@WebParam(name = "valor1") int valor1,
@WebParam(name = "valor2") int valor2) {

//TODO write your implementation code here:


return (valor1*valor2);
}

/**
* Web service operation
*/
@WebMethod(operationName = "resta")
public int resta(@WebParam(name = "valor1") int valor1, @WebParam(name
= "valor2") int valor2) {
//TODO write your implementation code here:
return (valor1-valor2);
}
}

5. De click derecho sobre el proyecto y escoja deploy. Despus haga lo


mismo y seleccione la opcin run, debe ejecutarse el explorador y salir
hola mundo.
6. Ahora probemos el web services, le damos click derecho sobre el web
services y seleccionar la opcin de Test Web Service. Pruebe colocando
datos y ejecutando para ver los resultados que arroja.
7. Ahora en eclipse cree el proyecto WebServicesAndroid y defina el
siguiente layout

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Spinner
android:id="@+id/operaciones_spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<LinearLayout

android:id="@+id/numero1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/operaciones_spinner"
android:layout_marginLeft="10dp"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Numero 1" />
<EditText
android:id="@+id/editTextNumero1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="number" />
</LinearLayout>
<LinearLayout
android:id="@+id/numero2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/numero1"
android:layout_marginLeft="10dp"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Numero 2" />
<EditText
android:id="@+id/editTextNumero2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="number" />
</LinearLayout>
<Button
android:id="@+id/btnResultado"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/numero2"
android:layout_below="@+id/numero2"
android:text="Calcular" />
<TextView
android:id="@+id/txtResultado"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/btnResultado"
android:layout_alignBottom="@+id/btnResultado"
android:layout_marginLeft="18dp"
android:layout_toRightOf="@+id/btnResultado"

android:text="Resultado" />
</RelativeLayout>

8. Cree una clase WebServicesTarea.java con el siguiente cdigo:

import
import
import
import
import

org.ksoap2.SoapEnvelope;
org.ksoap2.serialization.SoapObject;
org.ksoap2.serialization.SoapPrimitive;
org.ksoap2.serialization.SoapSerializationEnvelope;
org.ksoap2.transport.HttpTransportSE;

import android.os.AsyncTask;
public class WebServicesTarea extends AsyncTask<String, Void, Integer> {

private static final String NAMESPACE =


"http://websservicesandroid.example.com/";
private static final String URL =
"http://localhost:8080/CalculadoraWeb/calservices";
private MainActivity activity;
public WebServicesTarea(MainActivity activity) {
this.activity = activity;
}
@Override
protected void onPreExecute() {
activity.setResultado("Conectando a WebService...");
}
@Override
protected Integer doInBackground(String... params) {
Integer resultado = -1;
try {
// Modelo el request
SoapObject request = new SoapObject(NAMESPACE, params[0]);
request.addProperty("arg0", Integer.valueOf(params[1]));
request.addProperty("arg1", Integer.valueOf(params[2]));
// Modelo el Sobre
SoapSerializationEnvelope sobre = new
SoapSerializationEnvelope(SoapEnvelope.VER11);

sobre.setOutputSoapObject(request);
// Modelo el transporte
HttpTransportSE transporte = new HttpTransportSE(URL);
// Llamada
transporte.call(NAMESPACE+params[0], sobre);
// Resultado
SoapPrimitive r = (SoapPrimitive) sobre.getResponse();
resultado = Integer.valueOf(r.toString());
} catch (Exception e) {
e.printStackTrace();
}
//Simulando un mayor tiempo de tardanza del webservice
//Ya que el webservice y la app se ejecutan en la misma PC el tiempo de
respuesta seria super rapido
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return resultado;
}
@Override
protected void onPostExecute(Integer result) {
activity.setResultado("Resultado: " + result);
}
}

9. El MainActivity con el siguiente cdigo:

import
import
import
import
import
import
import
import
import
import

android.os.Bundle;
android.app.Activity;
android.view.Menu;
android.view.View;
android.view.View.OnClickListener;
android.widget.ArrayAdapter;
android.widget.Button;
android.widget.EditText;
android.widget.Spinner;
android.widget.TextView;

public class MainActivity extends Activity {


private TextView txtResultado;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtResultado = (TextView)findViewById(R.id.txtResultado);
final Spinner spinner = (Spinner) findViewById(R.id.operaciones_spinner);
ArrayAdapter<CharSequence> adapter =
ArrayAdapter.createFromResource(this,
R.array.operaciones_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
Button btnCalcular = (Button)findViewById(R.id.btnResultado);
final EditText numero1 = (EditText)findViewById(R.id.editTextNumero1);
final EditText numero2 = (EditText)findViewById(R.id.editTextNumero2);
final MainActivity _act = this;
btnCalcular.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
WebServicesTarea task = new WebServicesTarea(_act);
task.execute(new String[] {spinner.getSelectedItem().toString(),
numero1.getText().toString(),
numero2.getText().toString()});
}
});
}
public void setResultado(String resultado) {
txtResultado.setText(resultado);
}
@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;
}
}

10.Define el siguiente permiso en el manifiesto:

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

También podría gustarte