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

 

转载于:https://www.cnblogs.com/tietazhan/p/7479329.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Apache HttpClientJava 中用于处理 HTTP 请求和响应的标准库。如果你需要使用 HttpClient调用 HTTPS 服务,首先你需要确保 httpClient 已经包含了对 SSL/TLS 的支持,通常这个库默认已经支持 HTTPS。 以下是一个简单的步骤来使用 HttpClient 进行 HTTPS 调用: 1. **添加依赖**:如果你使用的是 Maven,可以在 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.x</version> <!-- 选择合适的版本 --> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> <version>4.4.x</version> <!-- 与 HttpClient 版本对应 --> </dependency> ``` 2. **创建 HttpClient 实例**: ```java CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpsGet = new HttpGet("https://example.com/api/endpoint"); ``` 3. **添加 SSL 证书验证(可选)**: - 如果服务器使用自签名证书,你可能需要配置 TrustManager 以信任这些证书。可以自定义一个 `SSLContext` 或使用 `TrustingSSLSocketFactory`。 - 如果你有 CA 证书,可以将其添加到系统证书路径或传递给 `SSLContext`. ```java SSLContext sslContext = ...; // 创建并配置 SSLContext CloseableHttpClient httpClient = HttpClients.custom() .setSSLContext(sslContext) .build(); ``` 4. **发送请求并获取响应**: ```java HttpResponse response = httpClient.execute(httpsGet); try { StatusLine statusLine = response.getStatusLine(); // 处理响应 // ... } finally { response.close(); httpClient.close(); } ``` 5. **处理响应内容**: 从 `HttpResponse` 中读取响应码、响应头和内容。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值