The content outlines a step-by-step guide to implement OkHttp in an Android application. It details adding the necessary dependency, coding a MainActivity that constructs and sends a GET request to an API for object detection, and logging the response or errors. The result is a functional interaction with an ANPR service.
Step 1: Add OkHttp Dependency #
Add this to your build.gradle
(Module: app):
dependencies {
implementation 'com.squareup.okhttp3:okhttp:4.12.0'
}
Step 2: Android Code Example #
import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
import java.io.IOException;
import java.net.URLEncoder;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "AnprAPI";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String imageUrl = "https://example.com/car.jpg";
String apiKey = "your_api_key";
String ga = "your_ga_value";
try {
String url = "https://your-api-endpoint.com/ObjectDetection"
+ "?Image_url=" + URLEncoder.encode(imageUrl, "UTF-8")
+ "&Api_key=" + URLEncoder.encode(apiKey, "UTF-8")
+ "&GA=" + URLEncoder.encode(ga, "UTF-8")
+ "&Detect_license_plate=true"
+ "&Read_license_plate=true";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e(TAG, "Request Failed: " + e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
final String responseBody = response.body().string();
Log.d(TAG, "Response: " + responseBody);
} else {
Log.e(TAG, "Error: " + response.code());
}
}
});
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
}
}
Result: This sends a GET request to the API and logs the response from the ANPR service.
Let me know if you want to do this in Kotlin, or if the endpoint is actually a POST request.
Required Dependencies #
To ensure compatibility and support for HTTP communication and backward-compatible UI components, please add the following dependencies to your build.gradle (app-level):
// HTTP client for making network requests
implementation 'com.squareup.okhttp3:okhttp:4.12.0'
// AndroidX AppCompat for backward compatibility
def appcompat_version = "1.7.1"
implementation "androidx.appcompat:appcompat:$appcompat_version"
// For loading and tinting drawables on older Android versions
implementation "androidx.appcompat:appcompat-resources:$appcompat_version"