我们在请求接口的时候容易出现请求超时的现象,出现这一问题的原因可能是接口确实挂了,也可能是接口还没有来的及响应,我们程序里面已经出现了请求超时的现象

问题描述:

通常会出现以下的报错:

java.net.SocketTimeoutException: Read timed outat java.net.SocketInputStream.socketRead0(SocketInputStream.java)at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)at java.net.SocketInputStream.read(SocketInputStream.java:170)at java.net.SocketInputStream.read(SocketInputStream.java:141)at org.apache.http.impl.conn.LoggingInputStream.read(LoggingInputStream.java:84)at org.apache.http.impl.io.SessionInputBufferImpl.streamRead(SessionInputBufferImpl.java:137)at org.apache.http.impl.io.SessionInputBufferImpl.fillBuffer(SessionInputBufferImpl.java:153)at org.apache.http.impl.io.SessionInputBufferImpl.readLine(SessionInputBufferImpl.java:282)at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:138)at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:56)at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:259)at org.apache.http.impl.DefaultBHttpClientConnection.receiveResponseHeader(DefaultBHttpClientConnection.java:163)at org.apache.http.impl.conn.CPoolProxy.receiveResponseHeader(CPoolProxy.java:165)at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:273)at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:125)at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:272)at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:185)at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)

结合接口日志的打印,我判断是第二种现象,就是接口还没有返回信息,我程序这边就出现了超时的报错。那么如何解决,我们只有增加接口的请求等待时间

问题解决:

 private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);public static String postGeneralUrl(String url, String contentType, String jsonParam, String encoding, int reSend) {logger.info("当前请求接口地址:{}",jsonParam.toString());// 声明返回结果String result = "";// 开始请求API接口时间long startTime = System.currentTimeMillis();// 请求API接口的响应时间long endTime = 0L;HttpEntity httpEntity = null;HttpResponse httpResponse = null;HttpClient httpClient = null;try {contentType = contentType == null ? "application/x-www-form-urlencoded" : contentType;// 创建连接httpClient = HttpClientFactory.getInstance().getHttpClient();// 设置请求头和报文HttpPost httpPost = HttpClientFactory.getInstance().httpPost(url);Header header = new BasicHeader("Accept-Encoding", null);RequestConfig requestConfig =  RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();httpPost.setConfig(requestConfig);httpPost.addHeader(header);httpPost.addHeader("Content-Type", contentType);List<NameValuePair> list = new LinkedList<>();list.add(new BasicNameValuePair("params", jsonParam));// pageHelper放在body中传过去// 使用URL实体转换工具UrlEncodedFormEntity entityParam = new UrlEncodedFormEntity(list, "UTF-8"); // 使用 UrlEncodedFormEntity 来设置// // body,消息体内容httpPost.setEntity(entityParam);logger.info("请求{}接口的参数为{}", url, jsonParam);httpResponse = httpClient.execute(httpPost);httpEntity = httpResponse.getEntity();result = EntityUtils.toString(httpEntity);} catch (SocketTimeoutException es) {endTime = System.currentTimeMillis();result = "网络连接异常,请检查网络或者开票服务是否正常启动";logger.info("请求{}接口的响应报文内容为{},本次请求API接口的响应时间为:{}毫秒", url, result, (endTime - startTime));logger.error("请求{}接口出现异常", url, es);return result;} catch (Exception e) {logger.error("请求{}接口出现异常", url, e);} finally {try {EntityUtils.consume(httpEntity);} catch (IOException e) {e.printStackTrace();}}// 请求接口的响应时间endTime = System.currentTimeMillis();logger.info("请求{}接口的响应报文内容为{},本次请求API接口的响应时间为:{}毫秒", url, result, (endTime - startTime));return result;}

其中主要是这部分代码:

         RequestConfig requestConfig =  RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();httpPost.setConfig(requestConfig);

当然这个设置和使用的 http.client 版本也有一定的关系

当前我使用的版本是:

     <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore --><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpcore</artifactId><version>4.4.10</version></dependency><!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient --><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.6</version><exclusions><exclusion><groupId>commons-codec</groupId><artifactId>commons-codec</artifactId></exclusion><exclusion><groupId>commons-logging</groupId><artifactId>commons-logging</artifactId></exclusion></exclusions></dependency>

希望对你有所帮助

HttpClient 如何设置请求接口等待时间相关推荐

  1. 实战HttpClient 接口调用以及获取token 设置请求头

    简介: HTTP 协议可能是现在 Internet 上使用得最多.最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源.虽然在 JDK 的 java.net 包中已 ...

  2. HttpClient4 - 设置请求头

    目录 设置请求头 代码演示 设置请求头 HttpClient可以设置请求头,在实际项目中,登录后往往需要将session放置在cookie中, 以供后续接口使用,而cookie正是请求头的一部分. 代 ...

  3. Java 调用接口工具类并设置请求和传输超时时间

    废话不多说直接上代码 /*** 接口调用工具类* @Author: MonsterTiny* @Date: 2020-07-23 10:06*/ public class HttpClientUtil ...

  4. httpclient: 设置请求的超时时间,连接超时时间等

    1.为什么要设置HTTP timeout? 1.与用户操作相关的接口,如果不设置超时时间,将会出现长时间的无响应,严重影响用户体验. 2.负载很高的系统,因为大量调用耗时长的接口,导致性能急剧下降,从 ...

  5. Java HttpClient 如何使用代理IP请求接口

    实际场景中,可能会遇到需要使用代理IP请求接口的需求,所以这里给大家分享一下如何通过代理IP请求接口. proxyServer 代理IP proxyPort 代理端口 HttpClient httpC ...

  6. httpClient请求接口,用httpEntity接受结果

    标题 包含get和post的有参和无参的请求 post有参请求用httpEntity接受,处理成JsonObject类型 方法 package com.shzu.xyf.finding_sql_ins ...

  7. HttpClient设置请求超时

    前言 最近,我无疑间看到同事提交到git上的httpclient调用第三方服务设置超时代码,发现有趣的一件事.项目中引用的httpclient版本是4.4.5版本,结果同事为了设置超时,在项目的pom ...

  8. vue-cli设置跨域代理 + 开发/生成环境简单请求接口设置

    1.设置dev.proxyTable实现开发环境的跨域代理: 在config文件夹下index.js文件内: 1 module.exports = { 2 dev: { 3 proxyTable: { ...

  9. 前端请求接口post_程序员:HttpClient进行post请求的工具类,访问第三方接口HTTPS...

    HTTPS (英语:Hypertext Transfer Protocol Secure,缩写:HTTPS,常称为HTTP over TLS,HTTP over SSL或HTTP Secure) 是一 ...

最新文章

  1. Workout Wednesday Redux (2017 Week 3)
  2. 我愿意参加计算机俱乐部的英文,如果你是一英语俱乐部的负责人你会组织什么活动...
  3. java 环境变量的涵义
  4. intellij idea使用的准备工作
  5. QT的QOpenGLShaderProgram类的使用
  6. 前端常见算法的JS实现
  7. 贝叶斯分析好坏_贝叶斯统计 | 第五章第一部分 决策基本概念
  8. 课时67.标签选择器(掌握)
  9. 期刊计算机仿真地址在哪,计算机仿真杂志社地址
  10. xp无法远程计算机共享,解决XP局域网共享不能访问的问题
  11. 数据库基础知识(思维导图)
  12. 微信网页分享无需公众号php,php版微信公众号自定义分享内容实现方法
  13. 在阿里云建网站体验123
  14. 基于镶嵌数据集制作地貌晕眩图
  15. Elixir元编程-第三章 编译时代码生成技术进阶
  16. linu修改open files无效_不越狱修改运动步数,安卓苹果手机通用
  17. vue 引入富文本编辑器(巨简单)
  18. 桥接模式、NAT模式、仅主机模式
  19. 使用LASSO进行全基因组关联分析
  20. CTF网络安全大赛学习笔记1010

热门文章

  1. Could not open a connection to your authentication agent
  2. Linux 小知识翻译 - 「命令行的提示符」
  3. SQL Server 中,实现 varbinary 与 varchar 类型之间的数据转换
  4. Linux进程的分析和执行过程
  5. 秒杀系统怎么设计?8张图带你搞定!
  6. 干掉 Postman?测试接口直接生成API文档,这个工具我爱了
  7. 只看到了别人28岁退休,背后的期权知识你知道吗?
  8. 如何快速融入团队(三)
  9. 2019年一线大厂20个长问mongo面试题和答案
  10. 互联网公司面试官是如何360°无死角考察候选人的?(下篇)