Call rest api from mail class java

To call a REST API from a Mail class in Java, you can use the following approaches:

  1. Using HttpURLConnection:
    
    import java.net.HttpURLConnection;
    import java.net.URL;

public class Mail { public void sendMail() { String apiUrl = "https://api.example.com/endpoint"; try { URL url = new URL(apiUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); // or POST, PUT, DELETE, etc. connection.connect();

        int responseCode = connection.getResponseCode();
        if (responseCode == 200) {
            // Process the response
        } else {
            // Handle error
        }
    } catch (IOException e) {
        // Handle exception
    }
}

}

2. **Using `OkHttp` library**:
```java
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Mail {
    public void sendMail() {
        String apiUrl = "https://api.example.com/endpoint";
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
               .url(apiUrl)
               .get() // or post, put, delete, etc.
               .build();
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            // Process the response
        } else {
            // Handle error
        }
    }
}
  1. Using Apache HttpClient library:
    
    import org.apache.http.HttpResponse;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.HttpClients;

public class Mail { public void sendMail() { String apiUrl = "https://api.example.com/endpoint"; HttpClient client = HttpClients.createDefault(); HttpGet request = new HttpGet(apiUrl); HttpResponse response = client.execute(request); if (response.getStatusLine().getStatusCode() == 200) { // Process the response } else { // Handle error } } }

4. **Using `RestTemplate` from Spring Framework**:
```java
import org.springframework.web.client.RestTemplate;

public class Mail {
    public void sendMail() {
        String apiUrl = "https://api.example.com/endpoint";
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject(apiUrl, String.class);
        // Process the response
    }
}

Note that you need to add the necessary dependencies to your project for each of these approaches. For example, for OkHttp, you would add the following dependency to your pom.xml file (if you're using Maven):

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.9.0</version>
</dependency>

Make sure to replace the apiUrl variable with the actual URL of the REST API you want to call.