在spring系列框架中,使用代碼向另外一個服務發送請求,通常能夠用restTemplate或者feign,可是這兩種方法的底層原理是啥呢,今天就來探究一下。java
首先創建服務端:spring
@RestController
public class Controller {
@PostMapping("hello")
public String hello() {
return "hello";
}
}
複製代碼
新建一個springboot服務,建立這麼一個controller,而後啓動服務。api
其次使用代碼發送請求來調用這個服務:springboot
public static void main(String[] args) throws IOException {
URI uri = URI.create("http://127.0.0.1:8080/hello");
URL url = uri.toURL();
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(HttpMethod.POST.name());
connection.setDoOutput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
System.out.println(reader.readLine());
}
複製代碼
這樣就能夠看到控制檯會返回一個「hello」。bash
這就是java代碼發送網絡請求的基本api,spring框架在此基礎上進行了進一步的封裝。網絡
下一篇就來拆解spring對jdk的基本api進行了哪些封裝。app