Tuesday, March 28, 2017

REST Example with Headers using TomEE Plus

apache-tomee-plus-1.7.4 comes with out of the box REST


Tools to test REST services

  • Firefox-Poster Add-On
  • Chrome - postman?

    Create the following class and deploy inside a war on TomEE-Plus

    package com.apache.rest;
    
    import javax.ws.rs.GET;
    import javax.ws.rs.POST;
    import javax.ws.rs.Path;
    import javax.ws.rs.PathParam;
    import javax.ws.rs.Produces;
    import javax.ws.rs.core.MediaType;
    
     @Path("/greeting")
     public class GreetingService {
         @GET
         @Produces( { MediaType.TEXT_XML })
          @Path("{id1}/{id2}")
         public String message(@PathParam("id1") String id1, @PathParam("id2") String id2,  @Context HttpHeaders httpHeaders) {
    //called as http://localhost/greeting/{id1}/{id2}
    //http://localhost//greeting/3/2
           /** how to get specific header info? **/
    //        String cacheControl = httpHeaders.getRequestHeader("Cache-Control").get(0);
    //         System.out.println("Cache-Control: "+cacheControl);
     /** get list of all header parameters from request **/
     Set headerKeys = httpHeaders.getRequestHeaders().keySet();
     for(String header:headerKeys){
           if (httpHeaders.getRequestHeader(header)!= null && httpHeaders.getRequestHeader(header).size() > 0 )
              System.out.println(header+":"+httpHeaders.getRequestHeader(header).get(0));
     }
             return "Hi REST!" + id1 + " " + id2;
         }
    
         @POST
    //called as http://localhost//greeting?message=test
         public String lowerCase(final String message) {
             return "Hi REST!".toLowerCase();
         }
     }
    
    

    More at http://www.vogella.com/tutorials/REST/article.html


  • No comments:

    Post a Comment