7 ways to call HTTP interfaces in Java: The most comprehensive guide to the entire network
In the development process, calling the HTTP interface is one of the most common requirements. This article will introduce in detail the 7 mainstream ways to call HTTP interfaces in Java, including the advantages and disadvantages of each tool and the complete code implementation.
1. Use RestTemplate
RestTemplate
Is a synchronous HTTP client provided by Spring, suitable for traditional projects. Although it has been marked as outdated since Spring 5, it remains the first choice for many developers.
Sample code
import ; import ; import ; import ; import ; import ; public class RestTemplateExample { public static void main(String[] args) { // Interface address String url = "/target-method"; // Set request header HttpHeaders headers = new HttpHeaders(); (MediaType.APPLICATION_JSON); ("appId", "yourAppId"); ("timestamp", "yourTimestamp"); ("random", "yourRandom"); ("msgDigest", "yourMsgDigest"); // Set the request body String requestBody = """ { "fileName": "yourFileName", "fileSize": yourFileSize, "dataType": "yourDataType", "certificate": "yourCertificate", "deposit": "yourDeposit", "fileHash": "yourFileHash", "userId": "yourUserId", "appId": "yourAppId" } """; // Construct request RestTemplate restTemplate = new RestTemplate(); HttpEntity<String> entity = new HttpEntity<>(requestBody, headers); // Send a request ResponseEntity<String> response = (url, , entity, ); // Output response result ("Response: " + ()); } }
Pros and cons
- advantage:Simple and easy to use, suitable for rapid development.
- shortcoming:Obsolete and not recommended for new projects.
2. Use WebClient
WebClient
It is a modern HTTP client introduced by Spring 5, which supports synchronous and asynchronous calls.
Sample code
import ; import ; import ; public class WebClientExample { public static void main(String[] args) { // Create WebClient WebClient webClient = () .baseUrl("") .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .defaultHeader("appId", "yourAppId") .defaultHeader("timestamp", "yourTimestamp") .defaultHeader("random", "yourRandom") .defaultHeader("msgDigest", "yourMsgDigest") .build(); // Set the request body String requestBody = """ { "fileName": "yourFileName", "fileSize": yourFileSize, "dataType": "yourDataType", "certificate": "yourCertificate", "deposit": "yourDeposit", "fileHash": "yourFileHash", "userId": "yourUserId", "appId": "yourAppId" } """; // Send a request String response = () .uri("/target-method") .bodyValue(requestBody) .retrieve() .bodyToMono() .block(); // Synchronous call // Output response result ("Response: " + response); } }
Pros and cons
- advantage:Supports responsive programming and has powerful functions.
- shortcoming:The API is more complex and the learning curve is high.
3. Use OkHttp
OkHttp
It is a lightweight, high-performance HTTP client that supports synchronous and asynchronous calls.
Sample code
import okhttp3.*; public class OkHttpExample { public static void main(String[] args) throws Exception { // Create an OkHttp client OkHttpClient client = new OkHttpClient(); // Set the request body String requestBody = """ { "fileName": "yourFileName", "fileSize": yourFileSize, "dataType": "yourDataType", "certificate": "yourCertificate", "deposit": "yourDeposit", "fileHash": "yourFileHash", "userId": "yourUserId", "appId": "yourAppId" } """; // Construct request Request request = new () .url("/target-method") .post((requestBody, ("application/json"))) .addHeader("appId", "yourAppId") .addHeader("timestamp", "yourTimestamp") .addHeader("random", "yourRandom") .addHeader("msgDigest", "yourMsgDigest") .build(); // Send a request try (Response response = (request).execute()) { if (()) { ("Response: " + ().string()); } else { ("Request failed: " + ()); } } } }
Pros and cons
- advantage:High performance, supports asynchronous calls.
- shortcoming:Connections need to be managed manually, and the number of codes is large.
4. Use Apache HttpClient
Apache HttpClient
It is a powerful and stable HTTP client, suitable for scenarios where complex functions (such as proxy, authentication, multi-threading support).
Sample code
import ; import ; import ; import ; import ; import ; public class HttpClientExample { public static void main(String[] args) throws Exception { // Create HttpClient CloseableHttpClient httpClient = (); // Set the request address String url = "/target-method"; HttpPost httpPost = new HttpPost(url); // Set request header ("Content-Type", "application/json"); ("appId", "yourAppId"); ("timestamp", "yourTimestamp"); ("random", "yourRandom"); ("msgDigest", "yourMsgDigest"); // Set the request body String requestBody = """ { "fileName": "yourFileName", "fileSize": yourFileSize, "dataType": "yourDataType", "certificate": "yourCertificate", "deposit": "yourDeposit", "fileHash": "yourFileHash", "userId": "yourUserId", "appId": "yourAppId" } """; (new StringEntity(requestBody)); // Send a request try (CloseableHttpResponse response = (httpPost)) { String responseString = (()); ("Response: " + responseString); } } }
Pros and cons
- advantage:Powerful, supports multi-threading, proxying, connection pooling, etc.
- shortcoming:The API is relatively complex and has a lot of code.
5. Use Retrofit
Retrofit
It is a type-safe HTTP client based on OkHttp, suitable for graceful calls to the REST API.
Sample code
Define interface
import ; import ; import ; import ; public interface ApiService { @POST("/target-method") @Headers({ "Content-Type: application/json", "appId: yourAppId", "timestamp: yourTimestamp", "random: yourRandom", "msgDigest: yourMsgDigest" }) Call<String> createCz(@Body String requestBody); }
Calling the service
import ; import ; import ; import ; public class RetrofitExample { public static void main(String[] args) throws Exception { // Create Retrofit instance Retrofit retrofit = new () .baseUrl("") .addConverterFactory(()) .build(); // Create an interface instance ApiService apiService = (); // Construct the request body String requestBody = """ { "fileName": "yourFileName", "fileSize": yourFileSize, "dataType": "yourDataType", "certificate": "yourCertificate", "deposit": "yourDeposit", "fileHash": "yourFileHash", "userId": "yourUserId", "appId": "yourAppId" } """; // Call the interface Call<String> call = (requestBody); Response<String> response = (); if (()) { ("Response: " + ()); } else { ("Request failed: " + ()); } } }
Pros and cons
- advantage:Annotated calls, concise and efficient, and automatically handles JSON.
- shortcoming:Suitable for small and medium-sized projects, not for complex scenarios.
6. Use HttpURLConnection
HttpURLConnection
It is a native HTTP client that comes with Java, suitable for small projects that do not want to introduce external dependencies.
Sample code
import ; import ; import ; import ; import ; public class HttpURLConnectionExample { public static void main(String[] args) throws Exception { // Set the request address URL url = new URL("/target-method"); HttpURLConnection connection = (HttpURLConnection) (); // Set request methods and properties ("POST"); ("Content-Type", "application/json"); ("appId", "yourAppId"); ("timestamp", "yourTimestamp"); ("random", "yourRandom"); ("msgDigest", "yourMsgDigest"); (true); // Set the request body String requestBody = """ { "fileName": "yourFileName", "fileSize": yourFileSize, "dataType": "yourDataType", "certificate": "yourCertificate", "deposit": "yourDeposit", "fileHash": "yourFileHash", "userId": "yourUserId", "appId": "yourAppId" } """; try (OutputStream os = ()) { (()); (); } // Get the response int responseCode = (); if (responseCode == 200) { try (BufferedReader in = new BufferedReader(new InputStreamReader(()))) { String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = ()) != null) { (inputLine); } ("Response: " + ()); } } else { ("Request failed: " + responseCode); } } }
Pros and cons
- advantage:No additional dependencies required, suitable for simple scenarios.
- shortcoming:The API is cumbersome and has limited functions.
7. Use OpenFeign
OpenFeign
It is a declarative HTTP client provided by Spring Cloud, suitable for interface calls between microservices.
Sample code
Feign Client Interface
import ; import ; import ; import ; @FeignClient(name = "czClient", url = "") public interface CzClient { @PostMapping(value = "/target-method") String createCz( @RequestHeader("appId") String appId, @RequestHeader("timestamp") String timestamp, @RequestHeader("random") String random, @RequestHeader("msgDigest") String msgDigest, @RequestBody String requestBody ); }
Service call logic
import ; import ; @Service public class CzService { @Autowired private CzClient czClient; public void callCzApi() { String response = ( "yourAppId", "yourTimestamp", "yourRandom", "yourMsgDigest", """ { "fileName": "yourFileName", "fileSize": yourFileSize, "dataType": "yourDataType", "certificate": "yourCertificate", "deposit": "yourDeposit", "fileHash": "yourFileHash", "userId": "yourUserId", "appId": "yourAppId" } """ ); ("Response: " + response); } }
Pros and cons
- advantage:Declarative calls, integrating Spring ecosystem.
- shortcoming:Depend on Spring Cloud, not available for non-Spring projects.
Summarize
tool | Applicable scenarios | advantage | shortcoming |
---|---|---|---|
RestTemplate | Simple synchronous call | Simple and easy to use | Outdated, new projects are not recommended |
WebClient | High-performance asynchronous call and responsive scenarios | Supports asynchronous and responsive calls | API is more complex |
OkHttp | Small projects with high performance requirements | Lightweight and efficient, supporting asynchronous calls | Need to be managed manually, with a large amount of code |
Apache HttpClient | Complex scenarios, such as proxy, multithreading, authentication, etc. | Powerful function, high stability | API is more complex |
Retrofit | Annotated Call REST API | Concise and efficient, automatic processing of JSON | Suitable for small and medium-sized projects, not for complex scenarios |
HttpURLConnection | Minimalist scenarios, no extra dependencies required | Built-in support, no dependency on external libraries | Complex use and limited functions |
OpenFeign | Interface calls between microservices | Declarative calls, integrating Spring ecosystem | Depend on Spring Cloud, not available for non-Spring projects |
Here is the article about 7 ways to call HTTP interfaces in Java: The most comprehensive guide to the entire network. For more related contents of Java calling HTTP interfaces, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!