典型代表:webservice、dubbo
典型代表:RestFul。
HTTP客户端工具:HttpClient、OKHttp、URLConnection。他们之间的优缺点对比:
原生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 }
原文:https://www.cnblogs.com/ivy-xu/p/12873368.html