在项目使用https方式调用别人服务的时候,之前要写不少的代码,如今框架封装了不少,因此不用再写那么多了。java
网上看了一下,都是很老的版本,用过期的DefaultHttpClient。spring
以spring为例:apache
1,在apache 4.0版本中有 DefaultHttpClient 这个类,是用来作httpsClient的,可是在4.3的时候就换成了 CloseableHttpResponse 。DefaultHttpClient 类就被标记为了 @Deprecated 。安全
try(CloseableHttpResponse execute = HttpClients.createDefault().execute(new HttpGet("https://127.0.0.1:8080/demo/testApi"))) {
InputStream content = execute.getEntity().getContent();//获取返回结果 是一个InputStream
String s = IOUtils.toString(content);//把Stream转换成String
System.out.println(s);
} catch (IOException e) {
e.printStackTrace();
}
这里采用了JDK7的新特性,语法糖,CloseableHttpResponse 继承了Closeable,Closeable又继承了 AutoCloseable。在try(){}语法后跳出{}的时候,CloseableHttpResponse 会自动调用close()方法把client关闭。因此咱们不须要手动调用close()。多线程
若是是spring,在spring配置文件里面配置一个Bean。若是是spring boot在application内配置一个@Bean就能自动注入调用,很是方便。在ClsseableHttpClient上有 @Contract(threading = ThreadingBehavior.SAFE)注解,代表是线程安全的,因此就算是在多线程状况下也放心使用。app
2,spring还有一个类能够实现,RestTemplate,也是直接配置一个Bean,进行自动注入的方式框架
RestTemplate restTemplate = new RestTemplate();//可配置到spring容器管理,而后自动注入 String body = restTemplate.getForEntity("https://127.0.0.1:8080/demo/testApi", String.class).getBody();
System.out.println(body);
getForEntity的内部调用到 doExecute()方法时,会执行ClientHttpResponse的close()方法,因此咱们也不须要手动去调用close()。RestTemplate也是线程安全的类,多线程状况下也放心使用。线程