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

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

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;
}
}

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

5、在类中定义一个方法,用于发送请求并获得返回数据
public static String 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;
}

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

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