Hay muchas cosas que puede usar para crear servicios de descanso, y luego pueden ser consumidas por casi cualquier cosa. Lo sorprendente es la capacidad de golpearlos en su navegador web, simplemente porque todos estamos muy familiarizados con ellos.
Cuando necesito una solución de descanso "rápida y sucia", uso Restlet - No afirmaré que es la única solución, pero es la más fácil con la que he trabajado. Literalmente dije en una reunión que "podría tener XYZ en 10 minutos". Alguien más en la reunión me llamó y, efectivamente, al usar Restlet pude ejecutar un servidor REST en funcionamiento con las características (muy simples) que dije que obtendría en la reunión. Fue bastante astuto.
Aquí hay un servidor barebones que tiene un método, devolviendo la hora actual. Al ejecutar el servidor y presionar 127.0.0.1:12345/sample/time
se devolverá la hora actual.
import org.restlet.Application;
import org.restlet.Component;
import org.restlet.Context;
import org.restlet.Restlet;
import org.restlet.data.Protocol;
import org.restlet.routing.Router;
/**
* This Application creates an HTTP server with a singple service
* that tells you the current time.
* @author corsiKa
*/
public class ServerMain extends Application {
/**
* The main method. If you don't know what a main method does, you
* probably are not advanced enough for the rest of this tutorial.
* @param args Command line args, completely ignored.
* @throws Exception when something goes wrong. Yes I'm being lazy here.
*/
public static void main(String...args) throws Exception {
// create the interface to the outside world
final Component component = new Component();
// tell the interface to listen to http:12345
component.getServers().add(Protocol.HTTP, 12345);
// create the application, giving it the component's context
// technically, its child context, which is a protected version of its context
ServerMain server = new ServerMain(component.getContext().createChildContext());
// attach the application to the interface
component.getDefaultHost().attach(server);
// go to town
component.start();
}
// just your everyday chaining constructor
public ServerMain(Context context) {
super(context);
}
/** add hooks to your services - this will get called by the component when
* it attaches the application to the component (I think... or somewhere in there
* it magically gets called... or something...)
*/
public Restlet createRoot() {
// create a router to route the incoming queries
Router router = new Router(getContext().createChildContext());
// attach your resource here
router.attach("/sample/time", CurrentTimeResource.class);
// return the router.
return router;
}
}
Y aquí es el 'recurso hora actual' que utiliza:
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;
/**
* A resource that responds to a get request and returns a StringRepresentaiton
* of the current time in milliseconds from Epoch
* @author corsiKa
*/
public class CurrentTimeResource extends ServerResource {
@Get // add the get annotation so it knows this is for gets
// method is pretty self explanatory
public Representation getTime() {
long now = System.currentTimeMillis();
String nowstr = String.valueOf(now);
Representation result = new StringRepresentation(nowstr);
return result;
}
}
[REST] (http://en.wikipedia.org/wiki/REST) realmente solo tiene sentido en el contexto de HTTP. Definitivamente puede usar los _principles_ detrás de REST usando una API auto escrita que se ejecuta directamente sobre sockets sin formato, pero no sería REST en ese momento. – sarnold
bien quiero ser capaz de comunicarme a través de HTTP. pero no estoy seguro de qué API usar. posiblemente en un puerto personalizado. – DarthVader