Question

I want to create a simple REST service, and for that I am using Jersey and Grizzly.

Here is my Service class:

@Path("/service")
class TestRESTService {

    @GET
    @Path("test")
    @Produces(Array(MediaType.APPLICATION_JSON))
    public String test() {
        return "{ \"TestField\" : \"TestValue\" }";
    }

}

And from what I understand here is how I supposed to start it:

ResourceConfig config = new ResourceConfig();
config.registerClasses(TestRESTService.class);
URI serverUri = UriBuilder.fromUri("http://localhost/").port(19748).build();
HttpServer server = GrizzlyHttpServerFactory.createHttpServer(serverUri, config);
server.start();

But it's not working. :( I tried to send a request to

http://localhost:19748/service/test

using Google Chrome's Postman plugin by adding 'Accept' : 'application/json' as a Http Header, but nothing is returned. The 'hourglass' is just spinning around.

Could you please help me?

Was it helpful?

Solution

This one works for me:

private static String API_PACKAGE = "package where TestRESTService class";

public static final URI BASE_URI = UriBuilder
        .fromUri("http://localhost/")
        .port(8000)
        .build();

private static HttpServer initServer() throws IOException {
    System.out.println("Starting grizzly... " + BASE_URI);

    HttpServer httpServer = GrizzlyServerFactory.createHttpServer(BASE_URI, new HttpHandler() {
        @Override
        public void service(Request rqst, Response rspns) throws Exception {
            rspns.sendError(404);
        }
    });

    // Initialize and register Jersey Servlet
    WebappContext context = new WebappContext("GrizzlyContext", "/");
    ServletRegistration registration = context.addServlet(
            ServletContainer.class.getName(), ServletContainer.class);
    registration.setInitParameter(ServletContainer.RESOURCE_CONFIG_CLASS,
            PackagesResourceConfig.class.getName());
    registration.setInitParameter(PackagesResourceConfig.PROPERTY_PACKAGES, API_PACKAGE);
    registration.addMapping("/*");
    context.deploy(httpServer);

    return httpServer;
}   
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top