如果您已更新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. [Bug]由于代码已经过优化或者本机框架位于调用堆栈之上,无法计算表达式的值的解决方法(转)...
  2. Alphabet股价周五跌5.32%:三年最大单日跌幅
  3. 为新研究准备好一块用武之地:最全任务型对话数据调研
  4. django-oscar的商品显示为unavailable(不可购买)
  5. make zImage和make uImage的区别和mkimage工具的使用
  6. android logcat 根据包名过滤,adb logcat通过包名过滤(dos命令find后跟变量)
  7. 古巷里的人像写真,怎么拍出漂亮的照片?
  8. sublime text3怎么运行python代码_Sublime Text3配置在可交互环境下运行python快捷键
  9. 红米手机使用应用沙盒动态修改运营商参数
  10. GAN 生成对抗网络 10-6 Tips for improving GAN
  11. RAKsmart日本服务器的综合性能评测
  12. ChatGPT APK 安卓手机 安装包
  13. 贝塞尔Bezier曲线的使用
  14. Z 字形变换(Python)
  15. Arduino ESP8266通过 RF433数据收发实验
  16. 更简单的 Traefik 2 使用方式
  17. Java实现延时的方法
  18. 对象或者数组的复制(深拷贝)---泥腿子前端
  19. HDU 4808 Drunk(数学)
  20. css 中的position

热门文章

  1. Ajax响应处理数据的三种格式(主要使用gson包)
  2. JAVA---DOS命令学习
  3. Ubuntu下C++代码调用可执行文件。
  4. Invalid character found in the request target. The valid characters are defi
  5. jvm(6)-java类文件结构(字节码文件)
  6. java集合——java.util.Properties类
  7. layui绑定json_JSON绑定:概述系列
  8. junit数据驱动测试_使用Junit和Easytest进行数据驱动的测试
  9. junit注释_通过此注释改善您的JUnit体验
  10. jboss将war放在那?_将策略插入JBoss Apiman