RPC还是HTTP?HttpClient还是OKHttp?
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 }