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庫(kù)是JDK自帶的HttpUrlConnection,當(dāng)然我們可以根據(jù)自身的需求使用其他的HTTP庫(kù),例如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)文章
解決mybatisplus插入報(bào)錯(cuò)argument type mismatch的問題
這篇文章主要介紹了解決mybatisplus插入報(bào)錯(cuò)argument type mismatch的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-11-11
使用IDEA插件反編譯jar包的實(shí)現(xiàn)方式
這篇文章主要介紹了使用IDEA插件反編譯jar包的實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2025-05-05
Java GZip 基于內(nèi)存實(shí)現(xiàn)壓縮和解壓的方法
這篇文章主要介紹了Java GZip 基于內(nèi)存實(shí)現(xiàn)壓縮和解壓的方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-08-08
JAVA構(gòu)造方法/構(gòu)造器以及this使用方式
這篇文章主要介紹了JAVA構(gòu)造方法/構(gòu)造器以及this使用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03
Java中ClassLoader類加載學(xué)習(xí)總結(jié)
本篇文章主要給大家講述了Java中ClassLoader類加載的原理以及用法總結(jié),一起學(xué)習(xí)下。2017-12-12

