HTTP如何调用服务

首先创建空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字符串

问题:如果服务地址换成图片地址,是否一样可以打印到本地

弊端
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Java语录精选

你的鼓励是我坚持下去的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值