How to invoke external interfaces in Java backend?

The Java backend can call external interfaces in several ways:

  1. Utilize the HttpURLConnection class in the Java standard library: The HttpURLConnection class in the Java standard library is used to send HTTP requests. This class allows for sending GET, POST, and other types of requests to external interfaces. It can be used to establish a connection with an external interface, send an HTTP request, and then retrieve the resulting response.
URL url = new URL("http://example.com/api");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");

int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    System.out.println(response.toString());
} else {
    System.out.println("GET request failed");
}
  1. Utilize third-party libraries like Apache HttpClient: Apache HttpClient is an open-source HTTP client library that simplifies sending and handling HTTP requests. This library can be used to send HTTP requests, call external APIs, and retrieve the results.
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://example.com/api");
CloseableHttpResponse response = httpClient.execute(httpGet);

try {
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        String result = EntityUtils.toString(entity);
        System.out.println(result);
    }
} finally {
    response.close();
}
  1. You can simplify sending and handling HTTP requests by using frameworks like Spring’s RestTemplate. RestTemplate is a template class specifically designed for sending HTTP requests, allowing you to easily call external APIs and retrieve the response.
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject("http://example.com/api", String.class);
System.out.println(result);

In the above methods, you can choose the appropriate method to call the external interface based on specific needs.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds