zoukankan      html  css  js  c++  java
  • 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也是线程安全的类,多线程情况下也放心使用。

  • 相关阅读:
    跨域踩坑经验总结(内涵:跨域知识科普)
    Nginx location规则匹配
    CentOS 命令
    Centos 修改源
    Ubuntu下获取内核源码
    Ubuntu用户自定义脚本开机启动
    ubuntu 14.04安装x11VNC
    texi格式文件的读取
    更换主机后SSH无法登录的问题
    ubuntu操作系统的目录结构
  • 原文地址:https://www.cnblogs.com/tietazhan/p/7479329.html
Copyright © 2011-2022 走看看