Warning
This page is located in archive.

Lesson 5 - REST, Jersey client, mashup

Lesson plan

  • Mashups
  • Jersey Java client API
  • XML Parsers

Mashups

Short external talk on web mashup: Mashup architecture

Jersey Java client API

One may want to create a programmatic REST client using JAVA.

See the jersey documentation:

Client API

Adding the Maven dependency:

<dependency>
    <groupId>org.glassfish.jersey.core</groupId>
    <artifactId>jersey-client</artifactId>
    <version>2.22.1</version>
</dependency>

Using the client API is very easy:

Client orderClient = ClientBuilder.newClient();

WebTarget target  = orderClient
                       .target("http://localhost:8082/rest-client-api-example/resources/orders/{id}");
Response response = target
                       .resolveTemplate("id", 1) // Resolves the {id} template
                       .request(MediaType.APPLICATION_JSON)
                       .get();
  
if(response.getStatus() == Status.OK.getStatusCode()){
 Order order = (Order) response.readEntity(Order.class);
  
 System.out.println("Id: " + order.getId());
 System.out.println("Name: " + order.getName());
 System.out.println("Price: " + order.getPrice());
}else{
 System.out.println(response.getStatus() + " " + response.getStatusInfo());
}

Parsing JSON

Json-simple

Add the Maven dependency:

 <dependency>
   <groupId>com.googlecode.json-simple</groupId>
   <artifactId>json-simple</artifactId>
    <version>1.1</version>
 </dependency>

Sample usage:

 //Server output in String
 String output = response.getEntity(String.class);
 final JSONObject jsonObj = (JSONObject) parser.parse( output );
 if ( jsonObj != null && jsonObj.containsKey( "length" ) )
 {
    System.out.println(jsonObj.get( "length" ).toString());
 }

Google-gson

Using another JSON pareser:

Maven:

 <!--  Gson: Java to Json conversion -->
 <dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.2.4</version>
    <scope>compile</scope>
 </dependency>

Sample: http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/

XML parsing

courses/a4m36aos/cviceni/class_29_10_2015.txt · Last modified: 2015/10/29 07:26 by kopriste