Primeramente abrimos Netbeans






package com.web.ws;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
@Path("/mensaje")
public class Restful {
public Restful() {
}
@GET
@Produces("text/html")
public String getHtml() {
return "<html><body><h1>Hello World!</body></h1></html>";
}
@PUT
@Consumes("text/html")
public void putHtml(String nombre) {
System.out.println("Saludos(PUT):"+nombre);
}
}
En el momento de guardar la clase, se mostrará esta ventana. La misma que nos ayuda a configurar la información en el descriptor (web.xml) de manera automática








La variable URL debe ser cambiada al URL que se muestra en Resource. Podemos ver esta variable cuando probamos el servicio Restful tres pantallas atrás

El código es el siguiente:
package cliente;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
public class Main {
private static String ruta="http://localhost:21405/RestfulServer/resources/mensaje";
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
get();
put();
}
public static void get() {
String respuesta = "";
BufferedReader buffer = null;
try {
URL url = new URL(ruta);
URLConnection conn = url.openConnection();
buffer = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = buffer.readLine()) != null) {
respuesta += line;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (buffer != null) {
try {
buffer.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
System.out.println(respuesta);
}
public static void put() {
String respuesta = "";
OutputStreamWriter wr = null;
BufferedReader rd = null;
try {
URL url = new URL(ruta);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("PUT");
conn.setDoOutput(true);
wr = new OutputStreamWriter(conn.getOutputStream());
wr.write("Santiago");
wr.flush();
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
respuesta += line;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (wr != null) {
wr.close();
}
if (rd != null) {
rd.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
System.out.println(respuesta);
}
}
Ejecutamos el servidor y luego el cliente



No hay comentarios:
Publicar un comentario