首先创建空maven项目,在里面创建二个Spring Boot项目依赖是Spring web
服务端
@RestController
public class HelloController {
@GetMapping("hello") //被调用的地址
public String hello(){
return "hello";
}
客服端调用hello地址的服务
@RestController
public class UseHelloController {
@GetMapping("/Kefuduan")
public void hello() throws IOException {
HttpURLConnection con = null;//初始化
URL url = new URL("http://localhost:8080/hello"); //调用的服务地址
con = (HttpURLConnection)url.openConnection(); //获取服务连接
con.connect(); //连接打开
if (con.getResponseCode() == 200){ //获取响应码200比较
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));//获取输入流(服务地址)到缓存中
String s = bufferedReader.readLine(); //缓存对象中读取hello
System.out.println(s); //结果打印hello
bufferedReader.close();//关闭流
}
启动客服端服务http://localhost:8081/Kefuduan
通过这小例子看出来客服端在调用服务,必须有服务的URL地址端口,打开这地址连接,
用if判断状态码是否是200,是构建一个输入流通道到缓存,在缓存中读取hello字符串
问题:如果服务地址换成图片地址,是否一样可以打印到本地
弊端