Java調用外部接口有哪些方式

1.有哪些?

1.HttpURLConnection

1.介紹

1.這是Java標準庫提供的一個類,用于發送HTTP請求和接收響應

2.它不需要額外的依賴,但是API相對底層,編寫代碼時需要處理很多細節,如設置請求頭、處理連接和流等

2.代碼示例

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;public class HttpURLConnectionExample {public static void main(String[] args) throws Exception {URL url = new URL("http://example.com/api");HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("GET");// 設置請求頭(如果需要)conn.setRequestProperty("User-Agent", "Java-HttpClient/1.0");int responseCode = conn.getResponseCode();System.out.println("Response Code: " + responseCode);// 處理響應...conn.disconnect();}
}

2.Apache HttpClient

1.介紹

1.Apache HttpClient是一個功能強大的HTTP客戶端庫,提供了比HttpURLConnection更高級別的抽象

2.它支持復雜的HTTP操作,包括持久連接、認證、重定向處理等,并且API設計更加友好

3.需要引入外部依賴,但它是開源社區廣泛使用的解決方案之一

2.依賴

<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId>
</dependency>

3.代碼示例

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;public class ApacheHttpClientExample {public static void main(String[] args) throws Exception {try (CloseableHttpClient httpClient = HttpClients.createDefault()) {HttpGet request = new HttpGet("http://example.com/api");try (CloseableHttpResponse response = httpClient.execute(request)) {String responseBody = EntityUtils.toString(response.getEntity());System.out.println("Response Body: " + responseBody);}}}
}

3.OkHttp

1.介紹

1.OkHttp是一個現代的HTTP & HTTP/2客戶端,適用于Android和Java應用程序

2.它提供了一種簡潔的API來構建請求和處理響應,同時也內置了緩存、連接池等功能以優化性能

3.廣泛應用于移動開發領域,但同樣適用于一般的Java應用

2.依賴

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

3.代碼示例

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;public class OkHttpExample {public static void main(String[] args) throws Exception {OkHttpClient client = new OkHttpClient();Request request = new Request.Builder().url("http://example.com/api").build();try (Response response = client.newCall(request).execute()) {if (!response.isSuccessful()) throw new RuntimeException("Unexpected code " + response);System.out.println("Response Body: " + response.body().string());}}
}

4.Retrofit

1.介紹

1.Retrofit是一個類型安全的HTTP客戶端,專門為Android和Java設計

2.它基于OkHttp構建,并添加了對RESTful服務的支持,使得定義和調用API變得非常簡單

3.你可以通過注解定義API端點,并自動生成實現代碼,從而簡化了與遠程服務交互的過程

2.依賴

<dependency><groupId>com.squareup.retrofit2</groupId><artifactId>retrofit</artifactId>
</dependency><dependency><groupId>com.squareup.retrofit2</groupId><artifactId>converter-gson</artifactId>
</dependency>

3.代碼示例

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.Call;
import retrofit2.http.GET;interface ApiService {@GET("api")Call<String> getData();
}public class RetrofitExample {public static void main(String[] args) {Retrofit retrofit = new Retrofit.Builder().baseUrl("http://example.com/").addConverterFactory(GsonConverterFactory.create()).build();ApiService apiService = retrofit.create(ApiService.class);Call<String> call = apiService.getData();try {retrofit2.Response<String> response = call.execute();System.out.println("Response Body: " + response.body());} catch (Exception e) {e.printStackTrace();}}
}

5.Spring RestTemplate或WebClient

1.介紹

1.如果你在使用Spring框架,那么RestTemplate或新的響應式WebClient是很好的選擇

2.RestTemplate是同步的,而WebClient支持非阻塞式的異步調用,適合于響應式編程模型

3.它們集成了Spring生態系統的許多特性,如消息轉換器、異常處理等,可以極大地簡化HTTP通信的代碼

3.代碼示例

// RestTemplate Example (Synchronous)
import org.springframework.web.client.RestTemplate;public class RestTemplateExample {public static void main(String[] args) {RestTemplate restTemplate = new RestTemplate();String result = restTemplate.getForObject("http://example.com/api", String.class);System.out.println("Response Body: " + result);}
}// WebClient Example (Reactive)
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;public class WebClientExample {public static void main(String[] args) {WebClient webClient = WebClient.create("http://example.com");Mono<String> result = webClient.get().uri("/api").retrieve().bodyToMono(String.class);result.subscribe(System.out::println);}
}

6.Feign

1.介紹

1.Feign是一個聲明式的HTTP客戶端,它讓開發者可以通過簡單的注解來定義HTTP請求,類似于Retrofit

2.它通常與Spring Cloud一起使用,以便在微服務架構中進行服務間通信

3.支持可插拔的編碼器和解碼器,便于集成不同的數據格式

2.依賴

<dependencyManagement><dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-dependencies</artifactId><version>Hoxton.SR9</version> <!-- 請根據需要選擇最新的版本 --><type>pom</type><scope>import</scope></dependency></dependencies>
</dependencyManagement><dependencies><!-- Spring Boot Starter Web for building web, including RESTful, applications --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- Feign Client for declarative REST clients --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId></dependency><!-- Optional: If you are using Eureka for service discovery --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-eureka-client</artifactId></dependency>
</dependencies>

3.代碼示例

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;@FeignClient(name = "example-api", url = "http://example.com")
public interface ExampleClient {@GetMapping("/api")String getApiData();
}public class FeignExample {private final ExampleClient exampleClient;public FeignExample(ExampleClient exampleClient) {this.exampleClient = exampleClient;}public void fetchData() {String data = exampleClient.getApiData();System.out.println("Fetched Data: " + data);}
}

2.區別

1.易用性

HttpURLConnection較為復雜,而像Retrofit、Feign這樣的庫則大大簡化了HTTP請求的創建和管理

2.性能

OkHttp和HttpClient都提供了良好的性能特征,如連接池和高效的流處理

3.依賴管理

除了HttpURLConnection外,其他方式都需要引入第三方庫,這可能影響項目的依賴樹

4.生態系統支持

如果項目已經在使用某個框架(如Spring),那么使用該框架提供的工具(如RestTemplate或WebClient)可能會帶來更好的集成體驗

5.并發處理

WebClient和其他響應式客戶端更適合處理高并發場景,因為它們是非阻塞的

3.總結

選擇哪種方式取決于你的具體需求,比如是否需要處理大量并發請求、是否已經使用特定的框架或者是否有特殊的需求如HTTP/2支持等

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/65607.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/65607.shtml
英文地址,請注明出處:http://en.pswp.cn/web/65607.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

pandas系列----DataFrame簡介

DataFrame是Pandas庫中最常用的數據結構之一&#xff0c;它是一個類似于二維數組或表格的數據結構。DataFrame由多個列組成&#xff0c;每個列可以是不同的數據類型&#xff08;如整數、浮點數、字符串等&#xff09;。每列都有一個列標簽&#xff08;column label&#xff09;…

安裝完docker后,如何拉取ubuntu鏡像并創建容器?

1. 先docker拉取ubuntu鏡像 docker search ubuntu #搜索ubuntu 鏡像 docker pull ubuntu:22.04 #拉取ubuntu 鏡像 docker images #下載完成后&#xff0c;查看已經下載的鏡像 docker run --name ubuntu_container -dit ubuntu:22.04 /bin/bash # docker container -l 2.…

Qt監控系統遠程網絡登錄/請求設備列表/服務器查看實時流/回放視頻/驗證碼請求

一、前言說明 這幾個功能是近期定制的功能&#xff0c;也非常具有代表性&#xff0c;核心就是之前登錄和設備信息都是在本地&#xff0c;存放在數據庫中&#xff0c;數據庫可以是本地或者遠程的&#xff0c;現在需要改成通過網絡API請求的方式&#xff0c;現在很多的服務器很強…

詳細解釋 Vue 中的 h 函數和 render 函數:

Vue中的h函數和render函數是Vue中非常重要的函數&#xff0c;對Vue有著不可以或缺的作用&#xff0c;接下來讓我們了解一下&#xff01; // 1. h 函數的基本使用 /*** h 函數是 createVNode 的別名&#xff0c;用于創建虛擬 DOM 節點&#xff08;VNode&#xff09;* h 函數參數…

結構型模式3.組合模式

結構型模式 適配器模式&#xff08;Adapter Pattern&#xff09;橋接模式&#xff08;Bridge Pattern&#xff09;組合模式&#xff08;Composite Pattern&#xff09;裝飾器模式&#xff08;Decorator Pattern&#xff09;外觀模式&#xff08;Facade Pattern&#xff09;享元…

服務器攻擊方式有哪幾種?

隨著互聯網的快速發展&#xff0c;網絡攻擊事件頻發&#xff0c;已泛濫成互聯網行業的重病&#xff0c;受到了各個行業的關注與重視&#xff0c;因為它對網絡安全乃至國家安全都形成了嚴重的威脅。面對復雜多樣的網絡攻擊&#xff0c;想要有效防御就必須了解網絡攻擊的相關內容…

Transformer 中縮放點積注意力機制探討:除以根號 dk 理由及其影響

Transformer 中縮放點積注意力機制的探討 1. 引言 自2017年Transformer模型被提出以來&#xff0c;它迅速成為自然語言處理&#xff08;NLP&#xff09;領域的主流架構&#xff0c;并在各種任務中取得了卓越的表現。其核心組件之一是注意力機制&#xff0c;尤其是縮放點積注意…

[python3]Excel解析庫-XlsxWriter

XlsxWriter 是一個用于創建 Excel .xlsx 文件的 Python 庫&#xff0c;它允許你編寫程序來生成 Excel 文件&#xff0c;而無需實際運行 Microsoft Excel 應用程序。XlsxWriter 支持寫入數據、應用格式化、插入圖表和圖形等多種功能&#xff0c;并且可以處理較大的數據集。它是一…

Linux下部署SSM項目

作者主頁&#xff1a;舒克日記 簡介&#xff1a;Java領域優質創作者、Java項目、學習資料、技術互助 文中獲取源碼 Linux部署SSM項目 打包項目 1、修改pom.xml文件&#xff0c;打包方式改為war <packaging>war</packaging>2、idea 通過maven的clean&#xff0c;…

Bytebase 3.0.1 - 可配置在 SQL 編輯器執行 DDL/DML

&#x1f680; 新功能 新增環境策略&#xff0c;允許在 SQL 編輯器內直接執行 DDL/DML 語句。 支持為 BigQuery 數據脫敏。 在項目下新增數據訪問控制及脫敏管理頁面。 在數據庫頁面&#xff0c;支持回滾到變更歷史的某個版本。 &#x1f514; 兼容性變更 禁止工單創建…

ansible 知識點【回顧梳理】

ansible 知識點 1. 劇本2. facts變量3. register變量4. include功能5. handlers6. when 條件7. with_items 循環8. Jinja2模板9. group_vars10. roles :star::star::star: 看起來字數很多&#xff0c;實際有很多是腳本執行結果&#xff0c;內容不多哦 1. 劇本 劇本很重要的就是…

LLM之RAG實戰(五十一)| 使用python和Cypher解析PDF數據,并加載到Neo4j數據庫

一、必備條件&#xff1a; python語言Neo4j數據庫python庫&#xff1a;neo4j、llmsherpa、glob、dotenv 二、代碼&#xff1a; from llmsherpa.readers import LayoutPDFReaderfrom neo4j import GraphDatabaseimport uuidimport hashlibimport osimport globfrom datetime …

MLU上使用MagicMind GFPGANv1.4 onnx加速!

文章目錄 前言一、平臺環境準備二、環境準備1.GFPGAN代碼處理2.MagicMind轉換修改env.sh修改run.sh參數解析運行 3.修改后模型運行 前言 MagicMind是面向寒武紀MLU的推理加速引擎。MagicMind能將人工智能框架&#xff08;TensorFlow、PyTorch、Caffe與ONNX等&#xff09;訓練好…

關于大數據的基礎知識(一)——定義特征結構要素

成長路上不孤單&#x1f60a;&#x1f60a;&#x1f60a;&#x1f60a;&#x1f60a;&#x1f60a; 【14后&#x1f60a;///計算機愛好者&#x1f60a;///持續分享所學&#x1f60a;///如有需要歡迎收藏轉發///&#x1f60a;】 今日分享關于大數據的基礎知識&#xff08;一&a…

H5通過URL Scheme喚醒手機地圖APP

1.高德地圖 安卓URL Scheme&#xff1a;baidumap:// 官方文檔&#xff1a;https://lbs.amap.com/api/amap-mobile/guide/android/navigation IOS URL Scheme&#xff1a;iosamap:// 官方文檔&#xff1a;https://lbs.amap.com/api/amap-mobile/guide/ios/navi HarmonyOS NEXT U…

音視頻入門基礎:MPEG2-PS專題(5)——FFmpeg源碼中,解析PS流中的PES流的實現

音視頻入門基礎&#xff1a;MPEG2-PS專題系列文章&#xff1a; 音視頻入門基礎&#xff1a;MPEG2-PS專題&#xff08;1&#xff09;——MPEG2-PS官方文檔下載 音視頻入門基礎&#xff1a;MPEG2-PS專題&#xff08;2&#xff09;——使用FFmpeg命令生成ps文件 音視頻入門基礎…

國標GB28181-2022視頻平臺EasyGBS小知識:局域網ip地址不夠用怎么解決?

在局域網中&#xff0c;IP地址不足的問題通常不會在小型網絡中出現&#xff0c;但在擁有超過255臺設備的大型局域網中&#xff0c;就需要考慮如何解決IP地址不夠用的問題了。 在企業局域網中&#xff0c;經常會出現私有IP地址如192.168.1.x到192.168.1.255不夠用的情況。由于0…

spring boot啟動源碼分析(三)之Environment準備

上一篇《spring-boot啟動源碼分析&#xff08;二&#xff09;之SpringApplicationRunListener》 環境介紹&#xff1a; spring boot版本&#xff1a;2.7.18 主要starter:spring-boot-starter-web 本篇開始講啟動過程中Environment環境準備&#xff0c;Environment是管理所有…

springmvc前端傳參,后端接收

RequestMapping注解 Target({ElementType.METHOD, ElementType.TYPE}) Retention(RetentionPolicy.RUNTIME) Documented Mapping public interface RequestMapping {String name() default "";AliasFor("path")String[] value() default {};AliasFor(&quo…

分布式鎖 Redis vs etcd

為什么要實現分布式鎖?為什么需要分布式鎖,分布式鎖的作用是什么,哪些場景會使用到分布式鎖?分布式鎖的實現方式有哪些分布式鎖的核心原理是什么 如何實現分布式鎖redis(自旋鎖版本)etcd 的分布式鎖(互斥鎖(信號控制)版本) 分布式鎖對比redis vs etcd 總結 為什么要實現分布式…