SpringBoot調(diào)用外部接口的幾種方式
使用FeignClient調(diào)用
FeignClient調(diào)用大多用于微服務(wù)開發(fā)中,各服務(wù)之間的接口調(diào)用。它以Java接口注解的方式調(diào)用HTTP請(qǐng)求,使服務(wù)間的調(diào)用變得簡(jiǎn)單
1、在使用方引入依賴
<!-- Feign注解 這里openFeign的版本要和自己使用的SpringBoot匹配--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> <!-- <version>4.0.1</version> --> </dependency>
2、服務(wù)接口調(diào)用方
2.1、在啟動(dòng)類上加上@EnableFeigncliens注解
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.openfeign.EnableFeignClients; @SpringBootApplication @EnableFeignClients public class StudyfeignApplication { public static void main(String[] args) { SpringApplication.run(StudyfeignApplication.class, args); System.out.println("項(xiàng)目啟動(dòng)成功"); } }
2.2、編寫Feign接口調(diào)用服務(wù)controller層
import com.hysoft.studyfeign.service.SysUserClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("feign") public class SysUserController { @Autowired private SysUserClient sysUserClient; @PostMapping("getUserId") public void getUserId(String userId){ this.sysUserClient.getUserById(userId); } }
2.3、服務(wù)接口調(diào)用service層
feign的客戶端需要使用@FeignClient注解進(jìn)行表示,這樣掃描時(shí)才知道這是一個(gè)feign客戶端。@FeignClient最常用的就兩個(gè)屬性,一個(gè)name,用于給客戶端定義一個(gè)唯一的名稱,另一個(gè)就是url,用于定義該客戶端調(diào)用的遠(yuǎn)程地址。url中的內(nèi)容,可以寫在配置文件application.yml中,便于管理
@Service @FeignClient(name = "feign-service",url = "${master-getuserbyId}") public interface SysUserClient { @PostMapping("/master/test") String getUserById(String id); }
application.yml中的配置如下
server: port: 8081 master-getuserbyId: http://localhost:8080
3、服務(wù)接口提供者
對(duì)于接口提供者來說沒有特別要求,和正常的接口開發(fā)一樣
4、說明
需要說明的是,在接口調(diào)用方,可以繼續(xù)拓展service層,書寫service實(shí)現(xiàn)層,進(jìn)一步進(jìn)行拓展
import org.springframework.stereotype.Service; @Service public class SysUserClientImpl implements SysUserClient{ @Override public String getUserById(String id) { return ""; } }
使用RestTemplate調(diào)用
RestTemplate中幾個(gè)常用的方法:getForObject()、getForEntity()、postForObject()、postForEntity()。其中,getForObject() 和 getForEntity() 方法可以用來發(fā)送 GET 請(qǐng)求
1、引入依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
2、RestTemplateConfig配置類
SimpleClientHttpRequestFactory類對(duì)應(yīng)的HTTP庫是JDK自帶的HttpUrlConnection,當(dāng)然我們可以根據(jù)自身的需求使用其他的HTTP庫,例如HttpComponentsAsyncClientHttpRequestFactory
@Configuration public class RestTemplateConfig { @Bean public RestTemplate restTemplate(ClientHttpRequestFactory factory){ return new RestTemplate(factory); } @Bean public ClientHttpRequestFactory simpleClientHttpRequestFactory(){ SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); factory.setReadTimeout(5000);//單位為ms factory.setConnectTimeout(5000);//單位為ms return factory; } }
3、接口調(diào)用
@RestController public class TestRestTemplate { @Resource private RestTemplate restTemplate; @GetMapping(value = "/saveUser") public void saveUser(String userId) { String url = "http://127.0.0.1:8080/master/test"; Map map = new HashMap<>(); map.put("userId", "hy001"); String results = restTemplate.postForObject(url, map, String.class); } }
使用WebClient調(diào)用
Spring3.0引入了RestTemplate,但是在后來的官方源碼中介紹,RestTemplate有可能在未來的版本中被棄用,所謂替代RestTemplate,在Spring5中引入了WebClient作為異步的非阻塞、響應(yīng)式的HTTP客戶端。
1、引入依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency>
2、接口調(diào)用示例
public class TestWebClient { @Test public void doGet() { String userId = "郭郭"; String url = "http://127.0.0.1:8080/master/test/getSysUserById?userId={userId}"; Mono<String> mono = WebClient //創(chuàng)建WebClient實(shí)例 .create() //方法調(diào)用,WebClient中提供了多種方法 .get() //請(qǐng)求url .uri(url, userId) //獲取響應(yīng)結(jié)果 .retrieve() //將結(jié)果轉(zhuǎn)換為指定類型 .bodyToMono(String.class); //返回最終結(jié)果:block是阻塞的/subscribe()非阻塞式獲取響應(yīng)結(jié)果 System.out.println("響應(yīng)結(jié)果:" + mono.block()); } @Test public void doPost() { Map map = new HashMap<>(); map.put("name", "郭郭"); String requestBody = JSON.toJSONString(map); String url = "http://127.0.0.1:8080/master/test/saveUser"; Mono<String> mono = WebClient //創(chuàng)建WebClient實(shí)例 .create() //方法調(diào)用,WebClient中提供了多種方法 .post() //請(qǐng)求url .uri(url) //指定請(qǐng)求的Content-Type為JSON .contentType(MediaType.APPLICATION_JSON) //使用bodyValue方法傳遞請(qǐng)求體 .bodyValue(requestBody) //獲取響應(yīng)結(jié)果 .retrieve() //將結(jié)果轉(zhuǎn)換為指定類型 .bodyToMono(String.class); //返回最終結(jié)果:block是阻塞的/subscribe()非阻塞式獲取響應(yīng)結(jié)果 System.out.println("響應(yīng)結(jié)果:" + mono.block()); } }
在上述doPost請(qǐng)求中,我們的請(qǐng)求接口入?yún)⑹且粋€(gè)Map,但是需要轉(zhuǎn)換為JSON格式傳遞,這是因?yàn)閃ebClient默認(rèn)是使用JSON序列化的。
使用Apache HttpClient調(diào)用
public class TestHttpClient { @Test public void doGet() throws IOException { //步驟一:創(chuàng)建httpClient實(shí)例 CloseableHttpClient httpClient = HttpClients.createDefault(); //步驟二:創(chuàng)建HTTP請(qǐng)求 HttpGet httpGet = new HttpGet("http://127.0.0.1:8094/masterdata/sysUser/getSysUserById?userId=郭郭"); //步驟三:發(fā)送請(qǐng)求并獲取響應(yīng)數(shù)據(jù) CloseableHttpResponse response = httpClient.execute(httpGet); //步驟四:處理響應(yīng)數(shù)據(jù) HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity); //步驟五:關(guān)閉httpClient和response response.close(); httpClient.close(); } @Test public void doPost() throws IOException { //步驟一:創(chuàng)建httpClient實(shí)例 CloseableHttpClient httpClient = HttpClients.createDefault(); //步驟二:創(chuàng)建HTTP請(qǐng)求 HttpPost httpPost = new HttpPost("http://127.0.0.1:8094/masterdata/sysUser/saveUser"); //步驟三:設(shè)置請(qǐng)求體數(shù)據(jù),使用JSON格式 Map map = new HashMap<>(); map.put("name", "郭郭"); String requestBody = JSON.toJSONString(map); StringEntity stringEntity = new StringEntity(requestBody, "UTF-8"); stringEntity.setContentType("application/json"); httpPost.setEntity(stringEntity); //步驟四:發(fā)送請(qǐng)求并獲取響應(yīng)數(shù)據(jù) CloseableHttpResponse response = httpClient.execute(httpPost); //步驟五:處理響應(yīng)數(shù)據(jù) HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity); //步驟五:關(guān)閉httpClient和response response.close(); httpClient.close(); } }
使用HttpURLConnection調(diào)用
public class TestHttpURLConnection { @Test public void doGet() throws IOException { String userId = "郭郭"; // 參數(shù)值 userId = URLEncoder.encode(userId, "UTF-8"); // 對(duì)參數(shù)值進(jìn)行URL編碼 //步驟一:創(chuàng)建URL對(duì)象 URL url = new URL("http://127.0.0.1:8094/masterdata/sysUser/getSysUserById?userId=" + userId); //步驟二:打開連接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //步驟三:設(shè)置請(qǐng)求方式 conn.setRequestMethod("GET"); //步驟四:讀取響應(yīng)內(nèi)容 BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line); } reader.close(); System.out.println(sb.toString()); } @Test public void doPost() throws IOException { //創(chuàng)建URL對(duì)象 URL url = new URL("http://127.0.0.1:8094/masterdata/sysUser/saveUser"); //打開連接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //設(shè)置請(qǐng)求方式 conn.setRequestMethod("POST"); // 設(shè)置請(qǐng)求頭 conn.setRequestProperty("Content-Type", "application/json"); //啟用輸出流 conn.setDoOutput(true); //設(shè)置請(qǐng)求體數(shù)據(jù) Map map = new HashMap<>(); map.put("name", "郭郭"); String requestBody = JSON.toJSONString(map); //發(fā)送請(qǐng)求體數(shù)據(jù) try (DataOutputStream outputStream = new DataOutputStream(conn.getOutputStream())) { outputStream.write(requestBody.getBytes(StandardCharsets.UTF_8)); } //讀取響應(yīng)內(nèi)容 BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line); } reader.close(); System.out.println(sb.toString()); } }
使用OkHttp調(diào)用
1、引入依賴
<!--okhttp依賴--> <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>4.0.0</version> </dependency>
2、示例代碼
public class TestOkHttp { @Test public void doGet() throws IOException { OkHttpClient client = new OkHttpClient(); String url = "http://127.0.0.1:8080/master/test/getSysUserById?userId=郭郭"; Request request = new Request.Builder().url(url).build(); try (Response response = client.newCall(request).execute()) { ResponseBody body = response.body(); System.out.println(body.string()); } } @Test public void doPost() throws IOException{ OkHttpClient client = new OkHttpClient(); String url = "http://127.0.0.1:8080/master/test/saveUser"; MediaType mediaType = MediaType.get("application/json; charset=utf-8"); //requestBody請(qǐng)求入?yún)? Map map = new HashMap<>(); map.put("name", "admin"); RequestBody requestBody = RequestBody.create(mediaType, JSON.toJSONString(map)); Request request = new Request.Builder() .url(url) .post(requestBody) .build(); try (Response response = client.newCall(request).execute()) { ResponseBody body = response.body(); System.out.println(body.string()); } } }
使用AsyncHttpClient調(diào)用
1、引入依賴
<dependency> <groupId>org.asynchttpclient</groupId> <artifactId>async-http-client</artifactId> <version>2.12.3</version> </dependency>
2、示例代碼
public class TestAsyncHttpClient { @Test public void doGet() throws IOException { try (AsyncHttpClient client = new DefaultAsyncHttpClient();) { BoundRequestBuilder requestBuilder = client.prepareGet("http://127.0.0.1:8080/master/test/getSysUserById?userId=hy001"); CompletableFuture<String> future = requestBuilder.execute() .toCompletableFuture() .thenApply(Response::getResponseBody); //使用join等待響應(yīng)完成 String responseBody = future.join(); System.out.println(responseBody); } } @Test public void doPost() throws IOException { try (AsyncHttpClient client = new DefaultAsyncHttpClient();) { BoundRequestBuilder requestBuilder = client.preparePost("http://127.0.0.1:8094/8080/master/test/saveUser"); //requestBody請(qǐng)求入?yún)? Map map = new HashMap<>(); map.put("name", "admin"); String requestBody = JSON.toJSONString(map); requestBuilder.addHeader("Content-Type", "application/json"); requestBuilder.setBody(requestBody); CompletableFuture<String> future = requestBuilder.execute() .toCompletableFuture() .thenApply(Response::getResponseBody); //使用join等待響應(yīng)完成 String responseBody = future.join(); System.out.println(responseBody); } } }
到此這篇關(guān)于SpringBoot調(diào)用外部接口的幾種方式的文章就介紹到這了,更多相關(guān)SpringBoot調(diào)用外部接口內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
關(guān)于IDEA使用jsp可以訪問頁面轉(zhuǎn)換為html彈出頁面為404的問題
這篇文章主要介紹了關(guān)于IDEA使用jsp可以訪問頁面轉(zhuǎn)換為html彈出頁面為404的問題及解決方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-12-12Java連接Oracle數(shù)據(jù)庫完整步驟記錄
數(shù)據(jù)庫的操作是當(dāng)前系統(tǒng)開發(fā)必不可少的開發(fā)部分之一,下面這篇文章主要給大家介紹了關(guān)于Java連接Oracle數(shù)據(jù)庫的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-01-01Java實(shí)現(xiàn)動(dòng)態(tài)代理
本文給大家介紹的是java使用動(dòng)態(tài)代理類實(shí)現(xiàn)動(dòng)態(tài)代理的方法和示例,這里推薦給大家,有需要的小伙伴參考下吧2015-02-02springboot配置內(nèi)存數(shù)據(jù)庫H2教程詳解
這篇文章主要介紹了springboot配置內(nèi)存數(shù)據(jù)庫H2的詳細(xì)教程,需要的朋友可以參考下2017-07-07SpringMVC參數(shù)傳遞之基本數(shù)據(jù)類型和復(fù)雜對(duì)象說明
這篇文章主要介紹了SpringMVC參數(shù)傳遞之基本數(shù)據(jù)類型和復(fù)雜對(duì)象說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-10-10RestTemplate如何使用JSON發(fā)送Post請(qǐng)求
這篇文章主要介紹了RestTemplate如何使用JSON發(fā)送Post請(qǐng)求問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-09-09SpringBoot配置Spring?Security的實(shí)現(xiàn)示例
本文主要介紹了SpringBoot配置Spring?Security的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-10-10java實(shí)現(xiàn)截取PDF指定頁并進(jìn)行圖片格式轉(zhuǎn)換功能
這篇文章主要介紹了java實(shí)現(xiàn)截取PDF指定頁并進(jìn)行圖片格式轉(zhuǎn)換功能,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-09-09淺析java程序中hibernate的應(yīng)用總結(jié)
hibernate可以理解為是一個(gè)中間件它負(fù)責(zé)把java程序的sql語句接收過來發(fā)送到數(shù)據(jù)庫,而數(shù)據(jù)庫返回來的信息hibernate接收之后直接生成一個(gè)對(duì)象傳給java2013-07-07