Hola, en el artículo de hoy trataré el tema de webservices.
Los webservices son muy útiles cuando queremos distribuir nuestra aplicación y, en vez de dar acceso a la base de datos desde la aplicación directamente con un driver JDBC, lo que hacemos es que sea el webservice el que nos procese las peticiones a la base de datos. De esta manera, no tenemos que incluir la contraseña y usuario de la base de datos en la aplicación a distribuir y corremos menos riesgos de seguridad, ya que un usuario un poco espabilado podría descompilar nuestra aplicación y hacerse con las credenciales de la base de datos.
Usaremos el servidor XAMPP y ubicaremos los archivos php en la carpeta htdocs/service
Para empezar, crearemos la base de datos(webservice) con una única tabla(adjetivos) con 3 campos: Id, adjetivo,fecha.
Id (int, auto increment, primary key)
adjetivo(varchar)
fecha(timestamp)
Ahora crearemos el webservice que será un archivo php que procese las peticiones que se le envíen desde la aplicación Java, vamos a hacer que el web service procese dos peticiones, una de insertar datos y otra de hacer una consulta.
El archivo insert.php tendría este aspecto
<?php
$adjetivo=$_POST['adjetivo'];
$db=mysqli_connect("localhost","root","","webservice");
mysqli_query($db,"insert into adjetivos (adjetivo)values('$adjetivo')");
?>
El archivo select.php tendría este aspecto:
<?php
$db=mysqli_connect("localhost","root","","webservice");
mysqli_query($db,"set names 'utf8'");
$res=mysqli_query($db,"select * from adjetivos");
$fila=mysqli_fetch_array($res);
do{
echo $fila["adjetivo"].",".$fila["fecha"]."\n";
}while($fila=mysqli_fetch_array($res));
?>
Una vez hecho ésto haremos nuestra aplicación en Java que le pasará un parámetro POST al webservice, éste la procesará y nos devolverá los resultados en el caso del select o insertará el adjetivo en el caso del insert, para lo que he creado una clase base adjetivos.java para convertir a objetos los resultados de la petición select.
La clase adjetivo.java tiene este aspecto:
import java.util.Objects;
/**
*
* @author Javi
*/
public class adjetivos {
private int id;
private String adjetivo;
private String fecha;
public adjetivos(String adjetivo) {
this.adjetivo = adjetivo;
}
public adjetivos(String adjetivo, String fecha) {
this.adjetivo = adjetivo;
this.fecha = fecha;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAdjetivo() {
return adjetivo;
}
public void setAdjetivo(String adjetivo) {
this.adjetivo = adjetivo;
}
public String getFecha() {
return fecha;
}
public void setFecha(String fecha) {
this.fecha = fecha;
}
@Override
public String toString() {
return "adjetivo{ adjetivo=" + adjetivo + ", fecha=" + fecha + "}\n";
}
Usaré 2 clases con main, una para el ejemplo con insert y otra para el ejemplo con select.
En la clase main correspondiente al insert, le pasaremos un parámetro POST a PHP para que lo procese y lo inserte en la base de datos, esta clase sería una como la siguiente:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
*
* @author Javi
*/
public class Servicio {
/**
* @param args the command line arguments
*/
private static final String USER_AGENT = "Mozilla/5.0";
private static final String POST_URL = "http://localhost/service/insert.php";
private static final String POST_PARAMS = "adjetivo=encomiable";
public static void main(String[] args) throws IOException {
sendPOST();
}
private static void sendPOST() throws IOException {
URL obj = new URL(POST_URL);
HttpURLConnection httpURLConnection = (HttpURLConnection) obj.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("User-Agent", USER_AGENT);
// Aqui le pasamos los parametros
httpURLConnection.setDoOutput(true);
OutputStream os = httpURLConnection.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
// Una vez pasados los parametros recibimos el codigo de respuesta
int responseCode = httpURLConnection.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
}
}
El código anterior pasará un parámetro al archivo php con el adjetivo encomiable y será php el encargado de insertarlo en la base de datos
Ahora seguiremos haciendo un select de la tabla adjetivos y transformando los resultados en un arrayList de objetos adjetivos, en este caso no le vamos a pasar parámetros al select por lo que el parámetro será una cadena vacía, el siguiente código muestra como se debe proseguir
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
/**
*
* @author Javi
*/
public class leerphp2 {
/**
* @param args the command line arguments
*/
private static final String USER_AGENT = "Mozilla/5.0";
private static final String POST_URL = "http://localhost/service/select.php";
private static final String POST_PARAMS = "";
public static void main(String[] args) throws IOException {
// TODO code application logic here
sendPOST();
}
private static void sendPOST() throws IOException {
ArrayList <adjetivos> mati = new ArrayList<>();
URL obj = new URL(POST_URL);
HttpURLConnection httpURLConnection = (HttpURLConnection) obj.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("User-Agent", USER_AGENT);
// For POST only - START
httpURLConnection.setDoOutput(true);
OutputStream os = httpURLConnection.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
// For POST only - END
int responseCode = httpURLConnection.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // success
BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in .readLine()) != null) {
response.append(inputLine);
String [] fields = inputLine. split(",");
mati.add(new adjetivos (fields[0],fields[1]));
} in .close();
// print result
System.out.println(response.toString());
} else {
System.out.println("POST request not worked");
}
System.out.println("Escribiendo array");
for (int i = 0; i < mati.size(); i++) {
System.out.println(mati.get(i).toString()+"\n");
}
}
}
Enlace de interésJAVA POST
Espero que te haya gustado 😉




