SoFunction
Updated on 2025-04-04

How to call HTTP interface in Java

Java calls HTTP interface

illustrate

Java calls HTTP interfaces and can use Java's HttpURLConnection or HttpClient and other tools.

HttpURLConnection

import ;
import ;
import ;
import ;

public class HttpExample {
    public static void main(String[] args) throws Exception {
        // Create URL object        URL url = new URL("/api");

        // Create HttpURLConnection object        HttpURLConnection conn = (HttpURLConnection) ();

        // Set the request method to GET        ("GET");

        // Send a request        int responseCode = ();

        // Read the response content        BufferedReader in = new BufferedReader(new InputStreamReader(()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = ()) != null) {
            (inputLine);
        }
        ();

        // Print the response content        (());
    }
}

HttpClient

import ;
import ;
import ;
import ;
import ;
import ;

public class HttpExample {
    public static void main(String[] args) throws Exception {
        // Create an HttpClient object        HttpClient client = ().build();

        // Create HttpGet object        HttpGet request = new HttpGet("/api");

        // Send a request        HttpResponse response = (request);

        // Read the response content        BufferedReader in = new BufferedReader(new InputStreamReader(().getContent()));
        String inputLine;
        StringBuffer responseBuffer = new StringBuffer();
        while ((inputLine = ()) != null) {
            (inputLine);
        }
        ();

        // Print the response content        (());
    }
}

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.