RPC
- 遠程過程調用
- 自定義數據格式
- 速度快
- 效率高
典型代表:webservice、dubbo
HTTP
- 網絡傳輸協議
- 規定數據傳輸格式
- 服務調用和提供方沒有技術限定
- 消息封裝臃腫
典型代表:RestFul。
HTTP客戶端工具:HttpClient、OKHttp、URLConnection。他們之間的優缺點對比:
HttpClient
- 網絡框架
- 網絡請求封裝完善
- api多,難擴展
- 穩定
OKHttp
- 支持jdk1.7以上
- 網絡連接效率高。同一IP和端口請求重用一個socket
- 網絡請求成熟
- 網絡切換在線程,不能直接刷新UI
URLConnection
- 輕量級HTTP客戶端
- api少,易擴展
原生HttpClient
1 public class HttpTests { 2 3 CloseableHttpClient httpClient; 4 5 // 序列化與反序列化 6 private static final ObjectMapper MAPPER = new ObjectMapper(); 7 8 @Before 9 public void init() { 10 httpClient = HttpClients.createDefault(); 11 } 12 13 @Test 14 public void testGet() throws IOException { 15 HttpGet request = new HttpGet("http://www.baidu.com/s?ie=UTF-8&wd=java"); 16 String response = this.httpClient.execute(request, new BasicResponseHandler()); 17 User user = MAPPER.readValue(response, User.class); 18 String usertToString = MAPPER.writeValueAsString(user); 19 } 20 }
原生OkHttp
1 private OkHttpClient client = new OkHttpClient(); 2 3 @Test 4 public void testGet() throws IOException { 5 String api = "/api/files/1"; 6 String url = String.format("%s%s", BASE_URL, api); 7 Request request = new Request.Builder() 8 .url(url) 9 .get() 10 .build(); 11 final Call call = client.newCall(request); 12 Response response = call.execute(); 13 System.out.println(response.body().string()); 14 }
詳細可以參考https://www.cnblogs.com/zk-blog/p/12465951.html
RestTemplate
Spring的RestTemplate,對基於HTTP的客戶端進行封裝,實現對象與json的序列化與反序列化。支持HttpClient、OkHttp、URLConnection(默認的)。
1 @SpringBootApplication 2 public class HttpDemoApplication { 3 4 public static void main(String[] args) { 5 SpringApplication.run(HttpDemoApplication.class, args); 6 } 7 8 @Bean 9 public RestTemplate restTemplate() { 10 return new RestTemplate(); 11 } 12 }
1 @RunWith(SpringRunner.class) 2 @SpringBootTest(classes = HttpDemoApplication.class) 3 public class HttpDemoApplicationTests { 4 5 @Autowired 6 private RestTemplate restTemplate; 7 8 @Test 9 public void httpGet() { 10 User user = this.restTemplate.getForObject("http://localhost:8888/user/42", User.class); 11 System.out.println(user); 12 } 13 14 }