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字符串

問題:如果服務地址換成圖片地址,是否一樣可以打印到本地

弊端
在這裏插入圖片描述

發佈了66 篇原創文章 · 獲贊 68 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章