Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
1.5 kB
1
Indexable
Never
Certainly! You can use libraries like Apache HttpClient or OkHttp for more convenient API calls in Java. Here's an example using OkHttp:

1. Add OkHttp to your project. You can download the JAR file or use a build tool like Maven or Gradle to include it as a dependency.

2. Example code using OkHttp:

```java
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

public class ApiCaller {

    public static void main(String[] args) {
        try {
            // Replace these with your actual API endpoint and token
            String apiUrl = "https://api.example.com/endpoint";
            String bearerToken = "yourBearerToken";

            OkHttpClient client = new OkHttpClient();

            Request request = new Request.Builder()
                    .url(apiUrl)
                    .header("Authorization", "Bearer " + bearerToken)
                    .build();

            try (Response response = client.newCall(request).execute()) {
                if (response.isSuccessful()) {
                    String responseBody = response.body().string();
                    System.out.println("API Response: " + responseBody);
                } else {
                    System.out.println("Error: " + response.code() + " - " + response.message());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
```

Make sure to handle exceptions and customize the code based on your specific requirements.
Leave a Comment