对于在 Java 中获取 http 响应代码 202 的异步 http api 请求

问题描述

我有以下 DSS 个到 url 的 http 连接:

private static HttpURLConnection connection(String urlSpec) {
        HttpURLConnection connection = new URL(urlSpec).openConnection() as HttpURLConnection
        connection.setRequestProperty('Prefer','respond-async,wait=60')
        connection.setRequestProperty('Accept','application/json')
 
        connection.setRequestMethod("POST")
        connection.setRequestProperty("Content-Type","application/json; utf-8")
        connection.setDoOutput(true)
        connection
    }

下面是我检查http响应的代码部分,如果响应是http 200,即HTTP_OK,那么我可以获取数据并插入到数据库表中。 但现在问题是在处理过程中我现在介于 Got http error code as 202 之间,即 HTTP_ACCEPTED,因此我无法将此数据处理到数据库表中。

我认为 HTTP 202 在请求异步时是可以预料的。这意味着服务器已收到您的查询并正在处理它。我们需要通过重试在 URL 响应中发送的新 202 来不断检查请求的状态,直到获得 HTTP 200。但我不知道我该怎么做?

解决方法

嗯,是的,你需要不断询问远程资源是否完成了任务。

202 是非承诺的,这意味着 HTTP 无法稍后发送指示处理请求结果的异步响应。

我看到您也在使用“裸机”实用程序,例如 HttpURLConnection,这让我相信您没有任何库支持重试 HTTP 调用。

在这种情况下,您可以做的是生成一个新线程,可能使用 ExecutorServicesubmit/execute 一个简单循环的任务,例如

while (!Thread.interrupted()) { ... }

调用您的网址,直到收到 HTTP_OK


骨架可以是

executorService.execute(() -> {
  while (!Thread.interrupted()) {
    // Return a valid value if `HTTP_OK`,otherwise `null`
    final var result = callRemoteUrl(url);
    
    if (result != null) {
      callback.call(result);
      return;
    }
  }
});

其中 callback 是异步接收 HTTP 结果的实例。


while (true)
  HttpURLConnection connection = connection("XXX.com")
  
  if (connection.responseCode >= HTTP_SERVER_ERROR) {
    // Server/internal error,we can't do anything
    // Maybe throw a custom Exception.
    break;
  }

  if (connection.responseCode != HTTP_OK) {
    try {
      // Adjust the delay between calls,in ms
      Thread.sleep(1000);
    } catch (final InterruptedException e) {
      // Ignore
    }
    
    // Try again
    continue;
  }
  
  println("Got http response code: ${connection.responseCode},message: ${connection.responseMessage}")

  log.info("Successful request to ${connection.getURL()}")
  //println(connection.getInputStream().getText())

  LazyMap json = jsonFromExtractionConnection(connection)
  //Process the data from the response JSON and put it in the Map object for processing
  tryToProcessMarketDataFromExtractionJson(json,ricMap)

  // Filter the empty records out and take valid map from Data for inserting into DB table .
  def validMap = ricMap.findAll { key,val ->
      val.fs != null
  }

  insertIntoDb(validMap)
  writeToFile(outFile,sql(ORACLE),Select.query,Arrays.asList(Data.COLUMNS))
  
  // We're done,end the loop
  break;
}