Replacing repeated Swing HTTP code with Retrofit 2
Move a Swing restaurant app from repeated Apache HttpClient code to Retrofit interfaces, shared configuration, and explicit response handling.
My Swing application repeated the same request-building and JSON conversion code in each endpoint. I moved those transport details into Retrofit interfaces so search and location calls were easier to follow.
The examples use Retrofit 2.11.0, OkHttp 4.12.0, and Kotlin on the JVM.
Where the original client repeated itself
The existing Gradle build included Apache HttpClient, JSON converters, and OkHttp. The search class used Apache HttpClient directly. It assembled a URL, added query parameters, created a client, handled the response, and handed JSON to Gson.
1
2
3
4
5
6
7
8
dependencies {
implementation 'com.google.code.gson:gson:2.8.6'
implementation 'com.squareup.okhttp3:okhttp:4.12.0'
implementation 'com.squareup.okhttp3:logging-interceptor:4.12.0'
implementation group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.13'
implementation 'com.googlecode.json-simple:json-simple:1.1.1'
implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.17.1'
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public class SearchHTTP {
Gson gson = new Gson();
/**
* Search stores by name and location
*
* @param store (name, location1, location2)
* @return ArrayList<Store> store
* @throws IOException
* @author Namju Kim
*/
public ArrayList<StoreDTO> searchStoreByNameWithLocation(StoreDTO store) throws IOException {
// Construct the URL
CloseableHttpClient Client = HttpClientBuilder.create().build();
String baseURL = SingleTon.getBaseURL() + "/store/search-name";
// Set request parameters
HttpGet httpget = new HttpGet(baseURL);
try {
URI uri = new URIBuilder(httpget.getURI())
.addParameter("location1", store.getLocation1())
.addParameter("location2", store.getLocation2()) //Allow the location to be selected from a combo box
.addParameter("name", store.getName()).build();
httpget.setURI(uri);
} catch (URISyntaxException t) {
}
// Execute the GET request
HttpResponse response = Client.execute(httpget);
// Map the response to application objects
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
String responseBody = EntityUtils.toString(entity);
ArrayList<StoreDTO> results = gson.fromJson(responseBody, new TypeToken<ArrayList<StoreDTO>>() {
}.getType());
System.out.println(results);
return results;
} else {
return null;
}
}
}
A new endpoint meant repeating the same transport steps. Null parameters and response validation also ended up mixed with the code deciding what the search should query.
Adding Retrofit and defining the endpoints
Retrofit describes an HTTP API through an interface. OkHttp supplies the transport, and a converter handles serialization and response mapping. The example uses the Gson converter. Choose the converter that matches the annotations and adapters on the DTOs you actually pass through it.
1
2
3
4
5
6
7
8
dependencies {
// RESTful API
implementation 'com.squareup.retrofit2:retrofit:2.11.0'
implementation 'com.squareup.retrofit2:converter-gson:2.11.0'
implementation 'com.squareup.okhttp3:okhttp:4.12.0'
implementation 'com.squareup.okhttp3:logging-interceptor:4.12.0'
}
The IP lookup, restaurant search, and registration examples express the method, route, and parameters separately. The Call<T> API exposes a blocking execute() and asynchronous enqueue(). Retrofit can encode the query parameters and omit nullable values in places where the corresponding annotation permits null. The application still owns validation and the meaning of omitted fields.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import restaurant.DTO.Ifconfig
import retrofit2.Call
import retrofit2.http.GET
/**
* API for location data
*/
interface LocationRepository {
/**
* Look up location data for the IP address
*/
@GET("/json")
fun getIp(): Call<Ifconfig>
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* Find stores
* @param latitude Latitude
* @param longitude Longitude
* @param name Store name
* @param category Food category
* @return Matching stores
*/
@GET("/store")
fun getStoreList(
@Query("latitude") latitude: Double? = null,
@Query("longitude") longitude: Double? = null,
@Query("name") name: String? = null,
@Query("category") category: FoodType? = null,
): Call<MutableList<StoreHeaderDto>>
1
2
3
4
5
6
7
8
9
10
/**
* Register a store
* @param token User token
* @param storeRequestDto Store details
*/
@POST("/store")
fun registerStore(
@Header("Authorization") token: String,
@Body storeRequestDto: StoreRequestDto
): Call<StoreHeaderDto>
The location response has some snake_case fields. Check the converter setup against their mappings. The historical DTO shown here uses Jackson @JsonProperty. Gson needs its own @SerializedName annotations or an appropriate naming policy. An application can also select the Jackson converter.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import com.fasterxml.jackson.annotation.JsonProperty
data class Ifconfig(
val ip: String,
@JsonProperty("ip_decimal")
val ipDecimal: Long,
val country: String,
@JsonProperty("country_iso")
val countryIso: String,
@JsonProperty("country_eu")
val countryEu: Boolean,
@JsonProperty("region_name")
val regionName: String,
@JsonProperty("region_code")
val regionCode: String,
@JsonProperty("zip_code")
val zipCode: String,
val city: String,
val latitude: Double,
val longitude: Double,
@JsonProperty("time_zone")
val timeZone: String,
val asn: String,
@JsonProperty("asn_org")
val asnOrg: String,
@JsonProperty("user_agent")
val userAgent: UserAgent,
)
data class UserAgent(
val product: String,
val version: String,
val comment: String,
@JsonProperty("raw_value")
val rawValue: String,
)
Sharing the Retrofit client
The Kotlin object keeps the configured adapter available to the Java and Kotlin callers. The location API is given its own base URL. Share the underlying HTTP configuration where appropriate so the application can reuse connections across calls.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import restaurant.api.LocationRepository
import restaurant.api.StoreRepository
import restaurant.api.UserRepository
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object RetrofitProvider {
private fun locationServer(): Retrofit {
return Retrofit.Builder()
.baseUrl("https://ifconfig.co/")
.addConverterFactory(GsonConverterFactory.create())
.build()
}
val locationRepository: LocationRepository = locationServer().create(LocationRepository::class.java)
}
Calling the API from Java
The Java sample demonstrates the generated Kotlin singleton access and performs a blocking call from main. A Swing action listener runs on the event dispatch thread. Put a network call on a worker or use the asynchronous callback, then post the UI update back to the event dispatch thread.
1
2
3
4
5
6
7
8
9
10
11
@Slf4j
public class App {
public static void main(String[] args) throws IOException {
LocationRepository locationRepository = RetrofitProvider.INSTANCE.getLocationRepository();
Auth.INSTANCE.setLocation(locationRepository.getIp().execute().body());
log.info("IP : {}", Auth.INSTANCE.getLocation().getIp());
log.info("Country: {}", Auth.INSTANCE.getLocation().getCountry());
log.info("Latitude : {}", Auth.INSTANCE.getLocation().getLatitude());
log.info("Longitude : {}", Auth.INSTANCE.getLocation().getLongitude());
}
}
Figure 1. The location response with its IP address blurred.
What moved out of the view
The HTTP verb, parameter mapping, and returned type can now be reviewed on one interface. Error handling still matters. Check isSuccessful(), account for a missing body, and handle network failures before putting the result into shared application state. I would test a normal response, a non-success status, and a missing optional query value before deleting the original client method.
Figure 2. The Retrofit interface and the earlier request-building implementation.
I wrote up more examples in a separate post. Retrofit usage notes (Korean)