1. HttpURLConnection
URL url = new URL("https://example.com/api/data");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = conn.getInputStream();
// ...
}
conn.disconnect();
2. OkHttp
groovy
dependencies {
implementation 'com.squareup.okhttp3:okhttp:4.9.1'
}
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://example.com/api/data")
.build();
try (Response response = client.newCall(request).execute()) {
if (response.isSuccessful()) {
String responseBody = response.body().string();
// ...
}
}
3. Retrofit
groovy
dependencies {
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
}
public interface ApiService {
@GET("api/data")
Call<DataResponse> getData();
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://example.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService service = retrofit.create(ApiService.class);
Call<DataResponse> call = service.getData();
call.enqueue(new Callback<DataResponse>() {
@Override
public void onResponse(Call<DataResponse> call, Response<DataResponse> response) {
if (response.isSuccessful()) {
DataResponse dataResponse = response.body();
// ...
}
}
@Override
public void onFailure(Call<DataResponse> call, Throwable t) {
}
});