Square provides other adapters ,

Showcase, discuss, and inspire with creative America Data Set.
Post Reply
poxoja9630
Posts: 9
Joined: Sun Dec 22, 2024 4:39 am

Square provides other adapters ,

Post by poxoja9630 »

The API is clean, although it doesn't offer built-in parsing of JSON responses, so I've added some code to parse the JSON with Jackson: Java Copy the code ObjectMapper mapper = new ObjectMapper(); OkHttpClient client = new OkHttpClient(); Request request = new Request.

Builder() .url( etary/apod?api_key=DEMO_KEY") .build(); // defaults to GET Response response = client.newCall(request).

execute(); APOD apod = mapper.readValue(response.body().byteStream(), APOD.class); System.out.println(apod.title); [ full code on GitHub ] That's already good, but OkHttp only really reveals its full potential when you add Retrofit to it. Retrofit Retrofit is another library from Square, built on top of OkHttp. In addition to all the low-level features of philippines mobile number example OkHttp, it adds a way to build Java classes that can extract HTTP details and present a user-friendly, Java-compatible API.

First, we need to create an interface declaring the methods we want to call against the APOD API, with annotations defining how these correspond to HTTP requests: Java Copy the code public interface APODClient { @GET("/planetary/apod") @Headers("accept: application/json") CompletableFuture<APOD> getApod(@Query("api_key") String apiKey); } The type of feedback that CompletableFuture<APOD> an asynchronous client actually provides.

Square provides other adapters , but you can also write your own.

Image

Having such an interface helps simulate the client for testing, which I find valuable. After declaring the interface, we ask Retrofit to create an implementation that can be used to send requests to a given base URL. Being able to change the base URL is also useful for integration testing. To generate the client, the code looks like this: Java Copy the code Retrofit retrofit = new Retrofit.

Builder() .baseUrl( addConverterFactory(JacksonConverterFactory.create()) .build(); APODClient apodClient = retrofit.create(APODClient.

class); CompletableFuture<APOD> response = apodClient.getApod("DEMO_KEY"); // do other stuff here while the request is in-flight APOD apod = response.get(); System.out.println(apod.title); [ full code on GitHub ] API Authentication If there are multiple methods in our interface that all require an API key, it is possible to configure this by adding a HttpInterceptorto the base OkHttpClient.
Post Reply