Retrofit 2 — Beyond Android: Retrofit for Java Projects

We've tailored our 80+ tutorials on Retrofit to the Android platform. The snippets and examples are usually specifically written for Android apps. But that doesn't do Retrofit justice. Retrofit supports any regular Java project, not just on the Android platform.

Even though you can implement the vast majority of our tutorials on a regular Java project, with this tutorial we want to acknowledge that we discriminated our Java users so far.

We give an introduction to Retrofit for all Java developers. Retrofit can be helpful to you, because it offers the same benefits to a Java application as to an Android app: painless networking, automatic conversion of payloads, smart designs of interceptors and call adapters and much more! For example, if you need to do networking with your Java (server) application, Retrofit could be a prime choice.

Retrofit Series Overview

Retrofit for Java

Java projects come in all shapes and forms, thus adding Retrofit as a dependency might be not as straightforward as on Android. However, if your Java project also uses gradle, you can simply add a line:

repositories {  
    mavenCentral()
}

dependencies {  
    compile 'com.squareup.retrofit2:retrofit:2.5.0'
}

If your project doesn't use Gradle, you can download the .jar from Retrofit's website. Keep in mind that Retrofit requires at least Java 7.

Converter

Retrofit offers automatic conversion of payload formats (e.g., JSON, XML, …) to Java objects. These converters are not bundled with Retrofit. Instead, they're separate dependencies, which you'll also need to add to your project. You can find an overview over the important converters (and how to add them to your project) in our introduction to converters tutorial.

For example, if you need an XML converter, you could add the SimpleXML converter by adding another line to your Gradle dependencies:

dependencies {  
    compile 'com.squareup.retrofit2:retrofit:2.5.0'
    compile 'com.squareup.retrofit2:converter-simplexml:2.5.0'
}

Example GitHub Call

The way how you add Retrofit to your project is the only difference to Android projects. The way you use Retrofit is the same on either platform. This means you could move or share entire components from your Android app to a Java project (and vice versa). This also means that almost all of our tutorials will work just as well on Java as they do on Android. Android-specific tutorials, like logging with Stetho, does not work on Java.

Nevertheless, let's go through a simple example call, which executes a GET request on an XML file from my GitHub gists. It should also automatically convert it from an XML string to a Java object.

Retrofit Instance

First of all, you need a Retrofit instance and configure it to use SimpleXML as a converter. You do that with the Retrofit builder:

Retrofit retrofit = new Retrofit.Builder()  
    .baseUrl("https://gist.githubusercontent.com/")
    .addConverterFactory(SimpleXmlConverterFactory.create())
    .build();

In this case, set the baseUrl to GitHub's gist URL https://gist.githubusercontent.com/. You can add the SimpleXML converter via addConverterFactory(). Finally, you get a usable Retrofit object by calling .build().

Endpoint Description

Next, describe the endpoint you want to talk to as an interface. In this case, it's a simple GET request to a fixed URL. You describe it with the @GET() annotation and passing the relative URL to the annotation. The interface method name can be freely chosen, so use something that makes the function clear to you. Finally, the return type is the Call<> type, with the model class Task wrapped in it.

interface GithubGistService {  
    @GET("peitek/eb360c3897f903acc517ebc6419fe071/raw/e8b6362e58d71397363c9fecf8b2fad9ad461568/gistfile1.txt")
    Call<Task> getGithubGist();
}

Of course, you still need to describe the Task model class itself, which you'll do in the next section.

Model Description

If you take a look at the XML file, the described task includes four properties: id, title, description, and language. You'll have to describe these properties in a Java model file, and then enhance it with the SimpleXML annotations to enable the automatic conversion.

@Root(name="task")
public static class Task {  
    @Element(name="id")
    private long id;

    @Element(name="title")
    private String title;

    @Element(name="description")
    private String description;

    @Element(name="language")
    private String language;

    // .. further methods
    public Task() {}
}

Execute the Network Call

You've finished the preparations, so it's time to do the final step and actually execute the network call. Unlike the majority of Android calls, which usually have to be asynchronous, you can use synchronous calls on Java.

Either way, create a service with retrofit.create() based on the interface described earlier. On the service you get the interface method and then call .execute() to synchronously execute the network request.

GithubGistService gistService = retrofit.create(GithubGistService.class);

try {  
    Response<Task> response = gistService.getGithubGist().execute();
    Task task = response.body();
    System.out.println("Request done!");
} catch (IOException e) {
    e.printStackTrace();
}

Because it's a synchronous call, the method directly returns the actual server response. The server response is wrapped in a Response<> class, which provides further meta information (like response headers, status code). With .body() you can access the actual task object. If a fundamental connection issue occurs, like no Internet connection, Retrofit will throw a IOException.

This Is Just the Start

In this short introductory tutorial you've only seen a glimpse of Retrofit's capabilities. There is a lot more fascinating functionality to explore. Don't be discouraged that our other tutorials talk about Android use cases, you can apply them to your Java projects as well.

For example, start here to learn about API endpoint descriptions.

Do you have further questions on this topic or about Retrofit in general? Let us know on Twitter @futurestud_io or leave a comment below.

Enjoy coding & make it rock!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.