client Java RESTful avec java.net.URL

Dans ce didacticiel, nous vous montrons comment créer un client Java RESTful avec la bibliothèque client HTTP intégrée . C’est simple à utiliser et suffisant pour effectuer des opérations de base pour le service REST.

Les services RESTful du dernier article « Jackson JAX-RS ]seront réutilisés et nous utiliserons« java.net.URL ». “` Java.net.HttpURLConnection` ”pour créer un client Java simple afin d’envoyer les requêtes“ GET ”et“ POST ”.

1. Demande GET

Consultez le dernier service REST et renvoyez les données «json» au client.

@Path("/json/product")
public class JSONService {

    @GET
    @Path("/get")
    @Produces("application/json")
    public Product getProductInJSON() {

        Product product = new Product();
        product.setName("iPad 3");
        product.setQty(999);

        return product;

    }
   //...

Client Java pour envoyer une requête «GET».

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class NetClientGet {

   //http://localhost:8080/RESTfulExample/json/product/get
    public static void main(String[]args) {

      try {

        URL url = new URL("http://localhost:8080/RESTfulExample/json/product/get");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");

        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + conn.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(
            (conn.getInputStream())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }

        conn.disconnect();

      } catch (MalformedURLException e) {

        e.printStackTrace();

      } catch (IOException e) {

        e.printStackTrace();

      }

    }

}

Sortie…​

Output from Server ....

{"qty":999,"name":"iPad 3"}

2. Requête POST

Consultez le dernier service REST, acceptez les données «json» et convertissez-les en objet Product, via le fournisseur Jackson automatiquement.

@Path("/json/product")
public class JSONService {

        @POST
    @Path("/post")
    @Consumes("application/json")
    public Response createProductInJSON(Product product) {

        String result = "Product created : " + product;
        return Response.status(201).entity(result).build();

    }
   //...

Client Java pour envoyer une demande "POST", avec chaîne json.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class NetClientPost {

   //http://localhost:8080/RESTfulExample/json/product/post
    public static void main(String[]args) {

      try {

        URL url = new URL("http://localhost:8080/RESTfulExample/json/product/post");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");

        String input = "{\"qty\":100,\"name\":\"iPad 4\"}";

        OutputStream os = conn.getOutputStream();
        os.write(input.getBytes());
        os.flush();

        if (conn.getResponseCode() != HttpURLConnection.HTTP__CREATED) {
            throw new RuntimeException("Failed : HTTP error code : "
                + conn.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(
                (conn.getInputStream())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }

        conn.disconnect();

      } catch (MalformedURLException e) {

        e.printStackTrace();

      } catch (IOException e) {

        e.printStackTrace();

     }

    }

}

Sortie…​

Output from Server ....

Product created : Product[name=iPad 4, qty=100]....

===  Télécharger le code source

Téléchargez-le - lien://wp-content/uploads/2011/07/JAX-RS-Client-JavaURL-Example.zip[JAX-RS-Client-JavaURL-Example.zip](8 Ko)

===  Références

. http://jackson.codehaus.org/%20[Jackson Site Officiel]

. http://download.oracle.com/javase/6/docs/api/java/net/URL.html[java.net.URL

JavaDoc]. http://download.oracle.com/javase/6/docs/api/java/net/HttpURLConnection.html[java.net.HttpURLConnection

JavaDoc]

lien://tag/jax-rs/[jax-rs]lien://tag/reposant/[reposant]lien://tag/url/[url]