Sobes.tech
Junior — Middle

How can synchronous data exchange between a server and an external system be implemented?

sobes.tech AI

Answer from AI

Synchronous data exchange between a server and an external system in Java is usually implemented through direct API or service calls, where the server waits for a response before continuing. Main methods:

  • HTTP requests (REST/SOAP) — the server sends a request and waits for a response. Libraries like HttpURLConnection, HttpClient (Java 11+), or third-party ones like Apache HttpClient can be used.

  • Remote Procedure Calls (RPC) — via technologies like gRPC, RMI.

  • Sockets — opening a TCP connection and exchanging messages in real-time.

Example of a synchronous HTTP GET request using HttpClient (Java 11+):

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://api.example.com/data"))
    .build();

HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

if (response.statusCode() == 200) {
    String responseBody = response.body();
    System.out.println(responseBody);
} else {
    System.out.println("Error: " + response.statusCode());
}

In this example, the server sends a request and waits for a response, which is the essence of synchronous exchange.