如果您已更新Apache HTTP Client代码以使用最新的库(在撰写本文时,它是4.2.x版本的httpclient 4.3.5版本和httpcore 4.3.2版本),您会注意到某些类(例如org.apache.http.impl.client.DefaultHttpClientorg.apache.http.params.HttpParams已被弃用。 好吧,我去过那里,所以在这篇文章中,我将介绍如何通过使用新类摆脱警告。

1.

我将用于演示的用例很简单:我有一个批处理作业,以检查是否有新的情节可用于播客。 为了避免在没有新情节的情况下必须获取和解析提要,我先验证自上次调用以来eTag或提要资源的last-modified标头是否已更改。 如果供稿发布者支持这些标头,这将起作用,我强烈建议您使用这些标头,因为这样可以节省使用者的带宽和处理能力。

那么它是如何工作的呢? 最初,当将新的播客添加到Podcastpedia.org目录时,我检查供稿资源的标头是否存在,如果存在,则将其存储在数据库中。 为此,我借助Apache Http Client对提要的URL执行HTTP HEAD请求。 根据超文本传输​​协议HTTP / 1.1 rfc2616 ,HTTP头中包含的响应HEAD请求的元信息应与响应GET请求发送的信息相同。

在以下各节中,我将介绍在升级到Apache Http Client的4.3.x版本之前和之后,代码在Java中的实际外观。

2.迁移到4.3.x版本

软件依赖

要构建我的项目,该项目现在可以在GitHub – Podcastpedia-batch上使用 ,我正在使用maven,因此在下面列出了Apache Http Client所需的依赖项:

2.1.1。 之前

Apache Http Client依赖项4.2.x

<!-- Apache Http client -->
<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.2.5</version>
</dependency>
<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpcore</artifactId><version>4.2.4</version>
</dependency>

2.1.2。 后

Apache Http Client依赖项

<!-- Apache Http client -->
<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.3.5</version>
</dependency>
<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpcore</artifactId><version>4.3.2</version>
</dependency>

Apache Http Client的HEAD请求

2.2.1。 v4.2.x之前

使用Apache HttpClient执行HEAD请求的示例

private void setHeaderFieldAttributes(Podcast podcast) throws ClientProtocolException, IOException, DateParseException{HttpHead headMethod = null;                   headMethod = new HttpHead(podcast.getUrl());org.apache.http.client.HttpClient httpClient = new DefaultHttpClient(poolingClientConnectionManager);HttpParams params = httpClient.getParams();org.apache.http.params.HttpConnectionParams.setConnectionTimeout(params, 10000);org.apache.http.params.HttpConnectionParams.setSoTimeout(params, 10000);HttpResponse httpResponse = httpClient.execute(headMethod);int statusCode = httpResponse.getStatusLine().getStatusCode();if (statusCode != HttpStatus.SC_OK) {LOG.error("The introduced URL is not valid " + podcast.getUrl()  + " : " + statusCode);}//set the new etag if existentorg.apache.http.Header eTagHeader = httpResponse.getLastHeader("etag");if(eTagHeader != null){podcast.setEtagHeaderField(eTagHeader.getValue());}//set the new "last modified" header field if existent org.apache.http.Header lastModifiedHeader= httpResponse.getLastHeader("last-modified");if(lastModifiedHeader != null) {podcast.setLastModifiedHeaderField(DateUtil.parseDate(lastModifiedHeader.getValue()));podcast.setLastModifiedHeaderFieldStr(lastModifiedHeader.getValue());}                                                            // Release the connection.headMethod.releaseConnection();
}

如果您使用的是智能IDE,它将告诉您DefaultHttpClientHttpParamsHttpConnectionParams已弃用。 如果您现在查看他们的Java文档,将会得到替换建议,即使用HttpClientBuilderorg.apache.http.config提供的类。

因此,正如您将在下一节中看到的那样,这正是我所做的。

2.2.2。 在v 4.3.x之后

带有Apache Http Client v 4.3.x的HEAD请求示例

private void setHeaderFieldAttributes(Podcast podcast) throws ClientProtocolException, IOException, DateParseException{HttpHead headMethod = null;                  headMethod = new HttpHead(podcast.getUrl());RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(TIMEOUT * 1000).setConnectTimeout(TIMEOUT * 1000).build();CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).setConnectionManager(poolingHttpClientConnectionManager).build();HttpResponse httpResponse = httpClient.execute(headMethod);int statusCode = httpResponse.getStatusLine().getStatusCode();if (statusCode != HttpStatus.SC_OK) {LOG.error("The introduced URL is not valid " + podcast.getUrl()  + " : " + statusCode);}//set the new etag if existentHeader eTagHeader = httpResponse.getLastHeader("etag");if(eTagHeader != null){podcast.setEtagHeaderField(eTagHeader.getValue());}//set the new "last modified" header field if existent Header lastModifiedHeader= httpResponse.getLastHeader("last-modified");if(lastModifiedHeader != null) {podcast.setLastModifiedHeaderField(DateUtil.parseDate(lastModifiedHeader.getValue()));podcast.setLastModifiedHeaderFieldStr(lastModifiedHeader.getValue());}                                                            // Release the connection.headMethod.releaseConnection();
}

注意:

  • HttpClientBuilder如何用于构建ClosableHttpClient [11-15行],这是HttpClient的基本实现,该实现也实现了Closeable
  • 以前版本的HttpParams已被org.apache.http.client.config.RequestConfig [第6-9行]取代,可以在其中设置套接字和连接超时。 稍后在构建HttpClient时使用此配置(第13行)

剩下的代码很简单:

  • HEAD请求被执行(第17行)
  • 如果存在,则eTaglast-modified标头将保留。
  • 最后,重置请求的内部状态,使其可重用– headMethod.releaseConnection()

2.2.3。 从代理后面进行http呼叫

如果您位于代理后面,则可以通过在RequestConfig上设置org.apache.http.HttpHost代理主机来轻松配置HTTP调用:

代理后面的HTTP调用

HttpHost proxy = new HttpHost("xx.xx.xx.xx", 8080, "http");
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(TIMEOUT * 1000).setConnectTimeout(TIMEOUT * 1000).setProxy(proxy).build();

资源资源

源代码– GitHub

  • podcastpedia-batch –将新的Podcast从文件添加到Podcast目录的工作,使用帖子中提供的代码来保留eTag和lastModified标头; 它仍在进行中。 如果您有任何改进建议,请提出要求

网页

  • 超文本传输​​协议-HTTP / 1.1
  • Maven仓库
    • HttpComponents客户端

翻译自: https://www.javacodegeeks.com/2014/08/how-to-use-the-new-apache-http-client-to-make-a-head-request.html

如何使用新的Apache Http Client发出HEAD请求相关推荐

  1. Feign,Apache Http Client,OkHttp的区别

    一.在Java中可以使用的HTTP客户端组件主要有3个,如下: (1)HttpURLConnection,JDK自带 (2)Apache HttpComponents,独立的HTTP客户端实现,使用广 ...

  2. org.apache.flink.client.program.ProgramInvocationException: Job failed

    完整报错信息如下: scala> senv.execute() org.apache.flink.client.program.ProgramInvocationException: Job f ...

  3. android studio没有org.apache.http.client.HttpClient;等包问题 解决方案

    android studio没有org.apache.http.client.HttpClient;等包问题 解决方案 参考文章: (1)android studio没有org.apache.http ...

  4. org.apache.http.client.CircularRedirectException: Circular redirect to http://xxx问题解决

    org.apache.http.client.CircularRedirectException: Circular redirect to "http://xxx"问题解决 用H ...

  5. apache AH01630: client denied by server configuration错误解决方法

    apache AH01630: client denied by server configuration错误解决方法 出现这个错误的原因是,apache2.4 与 apache2.2 的虚拟主机配置 ...

  6. (Hive)org.apache.hadoop.hbase.client.Put.setDurability(Lorg/apache/hadoophbase/client/Durability;)V

    报错信息: Error: java.lang.RuntimeException: java.lang.NoSuchMethodError:org.apache.hadoop.hbase.client. ...

  7. org.apache.flink.client.program.ProgramInvocationException: The main method caused an error

    flink任务开启检查点并设置状态后端后,提交任务运行,出现以上错误,具体错误如下: org.apache.flink.client.program.ProgramInvocationExceptio ...

  8. Java使用apache.http.client.fluent快速构建HTTP请求

    相关包 <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient --><depend ...

  9. org.apache.axis.client.Service调用服务webservice时报Unexpected wrapper element sayHello found. Expected

    先看报错信息: 2021-07-03 14:51:54.696 [http-nio-8090-exec-4] WARN  org.apache.cxf.phase.PhaseInterceptorCh ...

最新文章

  1. linux安装ActiveMQ
  2. [NOI2002] 银河英雄传说(带权并查集好题)
  3. 高性能ASP.NET站点构建之简单的优化措施
  4. 根据title 关闭cmd 窗口_2种Win7关闭休眠功能方法
  5. Keras情感分析(Sentiment Analysis)实战---自然语言处理技术
  6. 如何在 ASP.NET 4.6 与 IIS10 中运用 HTTP/2 ?
  7. 系统相机裁剪比例_要不要买全画幅相机?
  8. windows下安装ta-lib的方法
  9. Mosquitto安装及使用简介
  10. Java Reflect
  11. android 能否控制drawabletop的大小_V038小程序能否逐步完全取代APP?
  12. 在虚拟机中安装windows server 2008
  13. hdu6184 判断三元环
  14. PDF文件拆分为图片
  15. 【每日新闻】百度云王龙:数据库与AI的融合主要分三个阶段 | 中国移动研究院:5G第一个版本出炉...
  16. 分步:配置 IPAM 以管理 IP 地址空间
  17. 笔记本界面怎么显示服务器界面,电脑桌面显示工作方案(共8篇) .docx
  18. LANDesk准入认证客户端 每次启动都丢失
  19. 7-229 sdut-C语言实验- 排序7-227 sdut- C语言实验-计算1到n的和(循环结构)
  20. 写给湘大计算机相关专业的学弟学妹们

热门文章

  1. Spring的properties属性配置文件和Spring常用注解
  2. html session 登录页面跳转页面跳转页面,session失效后跳转到登陆页面
  3. Error:(1, 10) java: 需要class, interface或enum
  4. hashmap应用场景_工作中常用到的Java集合有哪些?应用场景是什么?
  5. 程序中抛出空指针异常_从Java应用程序中消除空指针异常
  6. 容器rocker_用Rocker制作模板
  7. php cdi_CDI和lambda的策略模式
  8. jax-rs jax-ws_极端懒惰:使用Spring Boot开发JAX-RS服务
  9. junit5和junit4_JUnit 5 –架构
  10. cassandra 入门_Apache Cassandra和Java入门(第一部分)