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
- Getting Started and Creating an Android Client
- Basics of API Description
- Creating a Sustainable Android Client
- URL Handling, Resolution and Parsing
- How to Change API Base Url at Runtime
- Multiple Server Environments (Develop, Staging, Production)
- Share OkHttp Client and Converters between Retrofit Instances
- Upgrade Guide from 1.9
- Beyond Android: Retrofit for Java Projects
- How to use OkHttp 3 with Retrofit 1
- Synchronous and Asynchronous Requests
- Send Objects in Request Body
- Add Custom Request Header
- Manage Request Headers in OkHttp Interceptor
- Dynamic Request Headers with @HeaderMap
- Multiple Query Parameters of Same Name
- Optional Query Parameters
- Send Data Form-Urlencoded
- Send Data Form-Urlencoded Using FieldMap
- How to Add Query Parameters to Every Request
- Add Multiple Query Parameter With QueryMap
- How to Use Dynamic Urls for Requests
- Constant, Default and Logic Values for POST and PUT Requests
- Cancel Requests
- Reuse and Analyze Requests
- Optional Path Parameters
- How to Send Plain Text Request Body
- Customize Network Timeouts
- How to Trust Unsafe SSL certificates (Self-signed, Expired)
- Dynamic Endpoint-Dependent Interceptor Actions
- How to Update Objects on the Server (PUT vs. PATCH)
- How to Delete Objects on the Server
- Introduction to (Multiple) Converters
- Adding & Customizing the Gson Converter
- Implementing Custom Converters
- How to Integrate XML Converter
- Access Mapped Objects and Raw Response Payload
- Supporting JSON and XML Responses Concurrently
- Handling of Empty Server Responses with Custom Converter
- Send JSON Requests and Receive XML Responses (or vice versa)
- Unwrapping Envelope Responses with Custom Converter
- Wrapping Requests in Envelope with Custom Converter
- Define a Custom Response Converter
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!