• Java 使用 HttpClient调用https 最新源码 JDK7+ apache4.3+


    在项目使用https方式调用别人服务的时候,以前要写很多的代码,现在框架封装了很多,所以不用再写那么多了。

    网上看了一下,都是很老的版本,用过时的DefaultHttpClient。

    以spring为例:

    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)注解,表明是线程安全的,所以就算是在多线程情况下也放心使用。

    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也是线程安全的类,多线程情况下也放心使用。

  • 相关阅读:
    渗透测试工具sqlmap基础教程
    安全测试——利用Burpsuite密码爆破(Intruder入侵)
    什么是AWVS
    渗透测试工具sqlmap基础教程
    安全测试——利用Burpsuite密码爆破(Intruder入侵)
    AWVS基本用法
    scrapy爬虫框架教程(二)-- 爬取豆瓣电影
    全链路压测平台在美团中的实践
    全链路压测平台在美团中的实践
    bzoj 1934: [Shoi2007]Vote 善意的投票
  • 原文地址:https://www.cnblogs.com/tietazhan/p/7479329.html
Copyright © 2020-2023  润新知