手抄报 安全手抄报 手抄报内容 手抄报图片 英语手抄报 清明节手抄报 节约用水手抄报

SpringBoot项目访问别的SpringBoot项目的接口

时间:2024-10-13 16:07:52

1、首先启动一个SpringBoot项目,在postman中访问其接口是能调通的

SpringBoot项目访问别的SpringBoot项目的接口

2、下面是另一个SpringBoot项目,在其application.properties文件中添加如下配置

SpringBoot项目访问别的SpringBoot项目的接口

3、写一个获取properties文件内容的工具类,代码如下:import java.io.FileInputStream;import 枣娣空郅java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.util.Properties;/*** 读取配置文件*/public class PropertiesUtil { public static String loadProperties(String url, String propName, String defaultValue) throws FileNotFoundException, IOException { Properties prop = new Properties(); prop.load(new FileInputStream(url)); String returnValue = prop.getProperty(propName, defaultValue); return returnValue; } public static String getProperty(String fileName, String key) { Properties prop = new Properties(); InputStream in = PropertiesUtil.class.getResourceAsStream("/" + fileName); try { prop.load(in); } catch (IOException e) { e.printStackTrace(); } String value = prop.getProperty(key); return value; } public static int getPropertyInt(String fileName, String key, int defaultValue) { Properties prop = new Properties(); InputStream in = PropertiesUtil.class.getResourceAsStream("/" + fileName); try { prop.load(in); } catch (IOException e) { e.printStackTrace(); } String value = prop.getProperty(key); if(value==null){ return defaultValue; }else{ return Integer.parseInt(value); } } public Properties getProperties(String fileName) { Properties prop = new Properties(); InputStream in = PropertiesUtil.class.getResourceAsStream("/sysConfig/" + fileName); try { prop.load(in); } catch (IOException e) { e.printStackTrace(); } return prop; }}

SpringBoot项目访问别的SpringBoot项目的接口

4、写一个工具类,在类中定义一个变量获取到application.properties文件中配置的ip地址private static String ip= PropertiesUtil.getProperty("application.properties", "ip");

SpringBoot项目访问别的SpringBoot项目的接口

5、在类中定义一个方法,用于发送请求并获得返回数据public static Stri艘绒庳焰ng executePost(String url,Map<String, Object> paramsMap){ String URL=ip+url; RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); HttpEntity<Map<String, Object>> request = new HttpEntity<>(paramsMap, headers); ResponseEntity<String> response = restTemplate.postForEntity(URL, request , String.class ); String data=response.getBody(); return data; }

SpringBoot项目访问别的SpringBoot项目的接口

6、写一个controller类,在类中定义一个接口,如下所示

SpringBoot项目访问别的SpringBoot项目的接口

7、启动项目,在postman中访问接口,可以看到接口调用成功,并返回了调用另一个项目中的接口所返回的数据

SpringBoot项目访问别的SpringBoot项目的接口
© 手抄报圈