【问题标题】:What to do when website not responding with HTTP error code?当网站没有响应 HTTP 错误代码时该怎么办?
【发布时间】:2014-11-17 06:36:09
【问题描述】:

我正在尝试连接到网站 ABC.com(HTTP API 端点)。但是,由于网站端的一些问题,我没有得到回复。

  val httpclient: CloseableHttpClient = HttpClients.custom()
  .setSSLSocketFactory(sslsf)
  .build()
  val getSlowQueryRequest: HttpGet = new HttpGet(mySQLHost + "cgi-bin/" + slowQueryLink)
  val slowQueryResponse: CloseableHttpResponse = httpclient.execute(getSlowQueryRequest)

程序在 httpclient.execute() 之后卡住了。我尝试手动打开该网站,即使那样它也没有给出任何响应。 正因为如此,程序的其余部分被挂断了!有什么方法可以设置一些计时器来等待某个时间,如果我没有得到响应,跳过测试后继续?

编辑:

也可能是因为使用了 SSL? CloseableHttpClient 不提供任何默认超时值吗?

提前致谢!

【问题讨论】:

    标签: scala http


    【解决方案1】:

    您可以为您的请求使用 HttpAsyncClient

    https://hc.apache.org/httpcomponents-asyncclient-dev/quickstart.html

    所以你的电话是:

     val futureResponse: Future<HttpResponse> = httpclient.execute(request1, null);
    

    您可以使用 onComplete for a Future 进行进一步处理。

    另一种选择是使用一些 Scala 原生库,例如 http://dispatch.databinder.net/Bargaining+with+futures.html

    import dispatch._, Defaults._
    val svc = url("http://api.hostip.info/country.php")
    val country = Http(svc OK as.String)
    val length = for (c <- country) yield c.length
    

    长度值是整数的未来。

    基本上,Scala 建议进行非阻塞处理,一旦您开始在这里和那里等待,您就会失去所有好处。

    这里有一些类似的问题,可以给你更多线索

    Simple and concise HTTP client library for Scala

    【讨论】:

    • CloseableHttpClient 是否提供了更直接的方法来设置超时而不涉及 Future,因为我对这个概念不太熟悉?
    • 我认为,CloseableHttpRequest 中有一个默认超时,但是您看到了它对您的系统的作用。您将有更小的中断,更小的超时,但问题仍然存在。
    【解决方案2】:
    val requestConfig: RequestConfig = RequestConfig.custom()
          .setSocketTimeout(30 * 1000) //30 sec timeout
          .setConnectTimeout(30 * 1000)
          .build()
        val sslsf: SSLConnectionSocketFactory = Utility.getTrustAllSSLFactory
        val httpclient: CloseableHttpClient = HttpClients.custom()
          .setDefaultRequestConfig(requestConfig)
          .setSSLSocketFactory(sslsf)
          .build()
    

    这对我来说很好用!

    【讨论】:

      猜你喜欢
      • 2021-05-02
      • 1970-01-01
      • 2022-11-13
      • 1970-01-01
      • 2012-01-02
      • 1970-01-01
      • 2013-10-28
      • 2011-07-31
      • 1970-01-01
      相关资源
      最近更新 更多